所以我在server.js文件中有以下代码,我正在运行node.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 .
任何想法如何获得请求的实际主体?
提前致谢 .
2 回答
你也需要bodyParser.json:
如果您忘记将name属性放入表单输入字段,req.body有时会显示{} . 以下是一个例子:
然后req.body显示
{ myemail: 'mathewjohnxxxx@gmail.com' }
我发布这个答案是因为,我遇到了类似的问题,这对我有用 .