所以我在我的 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。
任何想法如何获得请求的实际主体?
提前致谢。
原文由 Charlie Fish 发布,翻译遵循 CC BY-SA 4.0 许可协议
你还需要 bodyParser.json: