Express.js POST req.body 为空 [英] Express.js POST req.body empty

查看:49
本文介绍了Express.js POST req.body 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在使用 node.js 运行的 server.js 文件中有以下代码.我正在使用 express 来处理 HTTP 请求.

So I have the following code in my server.js file that I'm running with node.js. I'm using express to handle HTTP requests.

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);
  });
});

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

I'm running the following in Terminal:

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

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

After running that server.js prints out the following.

{}
{ host: 'localhost:3000',
  'user-agent': 'curl/7.43.0',
  accept: '*/*',
  'content-type': 'application/json',
  'content-length': '53' }

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

So req.body is {}. I read other Stack Overflow posts about similar issues where content-type was not correct because of body-parser. But that isn't the issue because content-type is application/json.

任何想法如何获取请求的实际正文?

Any ideas how to get the actual body of the request?

提前致谢.

推荐答案

你还需要 bodyParser.json:

You need bodyParser.json as well:

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

这篇关于Express.js POST req.body 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆