我有一个简单的Node.js程序在端口3000上运行,该程序接收POST请求并记录它们:
const express = require('express');
const app = express();
app.post('/post', async (req, res) => {
console.log('req.body:', req.body);
console.log('req.rawHeaders:', req.rawHeaders);
});
但是,无论何时我向其发送POST请求:
$ curl --data "param1=value1¶m2=value2" http://localhost:3000/post
程序收到的请求仅包含标头,并且缺少正文:
$ node server.js
req.body: undefined
req.rawHeaders: [
'Host',
'localhost:3000',
'User-Agent',
'curl/7.73.0',
'Accept',
'*/*',
'Content-Length',
'27',
'Content-Type',
'application/x-www-form-urlencoded'
]
我在这里做错了什么?为什么请求的正文始终为undefined
?
答案 0 :(得分:1)
我认为需要在node.js文件中增加一些配置,特别是必须添加body-parser依赖项,以便可以从传入请求中提取整个正文部分。
您必须使用npm安装body-parser:
npm install body-parser --save
之后,您应该将其添加到文件中并添加配置:
const bodyParser = require('body-parser')
const express = require('express');
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))