javascript - app.use(express.json) 在返回空对象的请求后不起作用
问题描述
const express = require('express');
app = express();
PORT = 3030;
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get("/", (req, res) => {
res.send('Hello World')
});
app.post('/', (req, res) => {
console.log(req.body);
res.json(req.body)
})
app.listen(PORT, err => {
if(err) {
return console.log('ERROR', err);
}
console.log(`Listening on port ${PORT}, http://localhost:${PORT}/`)
});
我正在使用 Postman 来测试它,这就是我正在使用的。
我正在使用表单数据:
{编号:123,新:新}
我试过使用 body-parser 但它已经被贬值了。
我正在使用快递“^4.17.1”
我只是想知道它是否是本地的东西可能会导致问题,因为我已经查找了几个教程并且他们没有这个问题。
我也尝试过使用 fetch 发出请求:
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
number: '123',
new: 'new'
})
}
fetch('http://localhost:3030/', options)
.then(response => response.json())
.then(data => console.log(data));
我得到的只是:
test.html:61 POST http://localhost:3030/ net::ERR_CONNECTION_REFUSED
Uncaught (in promise) TypeError: Failed to fetch
解决方案
您的邮递员图像显示form-data
(可能是multipart/form-data
)作为内容类型,这不是您的任何一个中间件处理程序都知道的内容。
express.json()
解析 JSON 内容类型,如application/json
.
express.urlencoded()
解析 URl 编码的内容类型,如application/x-www-form-urlencoded
.
人们经常使用multer进行解析multipart/form-data
,但如果这些数据只是简单的表单数据(名称/值对),那么您应该将其编码为application/x-www-form-urlencoded
或者application/json
而不是部署 multer。Multer 通常在您有文件上传时使用,这multipart/form-data
是必要的选择。
推荐阅读
- c# - 如何在 .Net 5.0 中配置 NodaTime 序列化
- angular - 如何修改ngif模板中的值?
- google-cloud-platform - GCP 组织政策限制列表
- 3d - 我想在 python 中的 3d 底图上绘制 2d 表面
- android - 空值检查运算符用于安全区域的空值
- python - Amazon S3 读取文件超时
- f# - 如何实现自定义 Monad 实例,尤其是 FSharpPlus 中的 IObservable?
- python - 使用 Flask API 从网站检索令牌值并存储令牌值
- spring - Why isn't RedisMessageListenerContainer starting up?
- node.js - 尝试填充猫鼬模式