[英]Node.js missing body of POST request
我有一個簡單的 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
?
我認為需要向 node.js 文件添加更多配置,特別是您必須添加 body-parser 依賴項,以便您可以從傳入請求中提取整個 body 部分。
您必須使用npm install body-parser --save
: 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 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.