这是我的服务器的代码:
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.post("/", function(req, res) {
res.send(req.body);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
从Postman,我向http://localhost:3000/发起POST请求,并且在Body/form-data中,我有一个键“foo”和值“bar”。
但是我一直在响应中得到一个空对象。
req.body
属性始终为空。我错过了什么?
最佳答案
添加请求的编码。这是一个例子
..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..
然后在Postman中选择
x-www-form-urlencoded
或将Content-Type设置为application/json
并选择raw
编辑以使用原始格式
生的
{
"foo": "bar"
}
header
Content-Type: application/json
编辑#2 聊天中的回答问题:
您肯定可以,只需查看此答案How to handle FormData from express 4
x-www-form-urlencoded
和raw
和differences in application/json and application/x-www-form-urlencoded
关于node.js - 无法使用Node JS/Express JS和Postman获取POST数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41955103/