Express.js POST req.body为空

所以我在我使用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); }); }); 

我在terminal上运行以下内容:

 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是{} 。 我读了其他堆栈溢出post有关类似的问题,其中内容types是不正确的,因为身体分析器。 但这不是问题,因为内容types是application / json。

任何想法如何得到请求的实际正文?

提前致谢。

你还需要bodyParser.json:

 app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); 

有时如果您忘记将name属性添加到表单input字段,则req.body会显示{}。 以下是一个例子:

 <input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required> 

然后req.body显示{ myemail: 'mathewjohnxxxx@gmail.com' }

我发布这个答案,因为我遇到了类似的问题,这对我工作。