[英]Getting an empty body using Express
我目前正在使用express来处理 POST 请求,但是当我使用node-fetch POST 时,我发送了一个正文,然后我 console.log() 收到了express中的正文(服务器代码)。 我得到一个空的 object。 不知道为什么会这样,我将在下面包含我的代码。
服务器代码
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
// GET method route
app.get('/api/getHeartCount', function (req, res) {
res.send('GET request')
});
// POST method route
app.post('/api/sendHeart', function (req, res) {
res.sendStatus(200);
let fBody = JSON.stringify(req.body);
console.log("Got body: " + fBody); // When this is run, I get this in the console: Got body: {}
});
app.listen(3000);
POST 请求代码
const fetch = require("node-fetch");
(async () => {
const body = { heartCount: 1 };
const response = await fetch('http://localhost:3000/api/sendHeart', {
method: "post",
body: JSON.stringify(body)
});
const res = await response.text();
console.log(res);
})();
你使用了错误的 bodyParser
您必须像这样使用 bodyParser.json() 中间件才能解析 json并在 req.body 访问正文
// this snippet will enable bodyParser application wide
app.use(bodyParser.json())
// you can also enable bodyParser for a set of routes if you don't need it globally like so
app.post('/..', bodyParser.json())
// or just for a set of routes
router.use(bodyParser.json()
bodyParser.json([options]) 返回仅解析 json 并且仅查看 Content-Type header 与 type 选项匹配的请求的中间件。 此解析器接受正文的任何 Unicode 编码,并支持 gzip 和 deflate 编码的自动膨胀。
在中间件(即 req.body)之后的请求 object 上填充了包含已解析数据的新主体 object。
来自:https://www.npmjs.com/package/body-parser#bodyparserjsonoptions
注意:如果您要发送 json 类型正文,请不要忘记将Content-Type: application/json
添加到您的请求中
更新:正如@ifaruki 所说,express 附带一个内置的 json bodyParser,可通过express.json()
访问: https://expressjs.com/en/api.html#express.Z466DEEC76ECDF36FCA6D38571F
您应该解析请求的正文
app.use(express.json());
使用最新的 express 版本,您不需要body-parser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.