Express.js POST req.body 为空

新手上路,请多包涵

所以我在我的 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 许可协议

阅读 757
2 个回答

你还需要 bodyParser.json:

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

原文由 7zark7 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

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

原文由 Mathew John 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏