[英]Express.js POST req.body empty
所以我在使用 node.js 運行的 server.js 文件中有以下代碼。 我正在使用 express 來處理 HTTP 請求。
app.post('/api/destinations', function (req, res) {
var new_destination = req.body;
console.log(req.body);
console.log(req.headers);
db.Destination.create(new_destination, function(err, destination){
if (err){
res.send("Error: "+err);
}
res.json(destination);
});
});
我在終端中運行以下內容:
curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations
運行該 server.js 后打印出以下內容。
{}
{ host: 'localhost:3000',
'user-agent': 'curl/7.43.0',
accept: '*/*',
'content-type': 'application/json',
'content-length': '53' }
所以 req.body 是{}
。 我閱讀了其他關於類似問題的 Stack Overflow 帖子,其中由於正文解析器,內容類型不正確。 但這不是問題,因為內容類型是 application/json。
任何想法如何獲取請求的實際正文?
提前致謝。
您還需要 bodyParser.json:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
有時,如果您忘記將 name 屬性放入表單輸入字段,則 req.body 會顯示 {}。 下面是一個例子:
<input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>
然后 req.body 顯示{ myemail: 'mathewjohnxxxx@gmail.com' }
我發布這個答案是因為,我遇到了類似的問題,這對我有用。
確保您在 javascript 中制作表單和輸入,將輸入附加到表單中。 那是我的問題。
yourForm.appendChild(yourInput);
對我來說,后端配置正確,問題是有效的 JSON 格式,包括變量上的雙引號。
這不起作用
const res = await axios.post(serverPath + "/user/login", {
email: email,
password: password,
});
這確實有效(電子郵件和密碼周圍有雙引號
const res = await axios.post(serverPath + "/user/login", {
"email": email,
"password": password,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.