Express.js POST req.body为空

Cha*_*ish 8 javascript json node.js express body-parser

所以我在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);
  });
});
Run Code Online (Sandbox Code Playgroud)

我在终端中运行以下内容:

curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations
Run Code Online (Sandbox Code Playgroud)

运行该server.js后打印出以下内容.

{}
{ host: 'localhost:3000',
  'user-agent': 'curl/7.43.0',
  accept: '*/*',
  'content-type': 'application/json',
  'content-length': '53' }
Run Code Online (Sandbox Code Playgroud)

所以req.body是{}.我阅读了其他关于类似问题的Stack Overflow帖子,其中由于正文解析器,内容类型不正确.但这不是问题,因为内容类型是application/json.

任何想法如何获得请求的实际主体?

提前致谢.

7za*_*rk7 20

你也需要bodyParser.json:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Run Code Online (Sandbox Code Playgroud)

  • 尽管包括两条线,我仍然有一个空的身体.不知道为什么. (8认同)
  • 谢谢!不知道为什么,但是当我尝试`app.use(bodyParser.json()); "看完你的评论后,即使我以前尝试了很多次,它也能奏效.必须是一个神奇的答案;) (2认同)
  • 我已经做了你们在这里建议的一切,但没有任何效果。我想知道为什么会发生这个错误?请好的答案! (2认同)
  • 你告诉我af(*&#@@(web框架不允许我访问通过POST传入的数据,除非我扩展它?! (2认同)

Mat*_*ohn 7

如果您忘记将name属性放入表单输入字段,req.body有时会显示{}.以下是一个例子:

<input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>
Run Code Online (Sandbox Code Playgroud)

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

我发布这个答案是因为,我遇到了类似的问题,这对我有用.