Node.js缺少POST请求的正文

时间:2020-11-06 23:12:29

标签: node.js post

我有一个简单的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&param2=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

1 个答案:

答案 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}))

此信息的更多信息: https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express#:~:text=body%2Dparser%20extract%20the%20entire,submitted%20using%20HTTP%20POST%20request

相关问题