突然之间,我所有的项目都出现了这种情况。

每当我在nodejs中使用express和body-parser req发布帖子时。Body是一个空对象。

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())

// parse application/json
app.use(bodyParser.json())

app.listen(2000);

app.post("/", function (req, res) {
  console.log(req.body) // populated!
  res.send(200, req.body);
});

通过ajax和邮递员,它总是空的。

但是通过curl

$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/

它按预期工作。

我尝试在前者中手动设置Content-type: application/json,但我总是得到400个坏请求

这快把我逼疯了。

我以为是身体解析器更新了一些东西,但我降级了,它没有帮助。

感谢任何帮助,谢谢。


当前回答

您必须检查主体解析器中间件是否正确地设置为请求的类型(json, urlencoded)。

如果你设置了,

app.use(bodyParser.json());

然后在邮差你必须发送原始数据。

https://i.stack.imgur.com/k9IdQ.png邮差截图

如果你设置了,

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

然后应该选择'x-www-form-urlencoded'选项。

其他回答

我今天遇到了这个问题,解决它的方法是删除Postman中的内容类型头!很奇怪。把它加到这里,说不定能帮到谁。

我在这里跟随BeerLocker教程:http://scottksmith.com/blog/2014/05/29/beer-locker-building-a-restful-api-with-node-passport/

我用上面建议的multer解决了这个问题,但他们没有给出一个完整的工作示例,关于如何做到这一点。基本上,当你有一个enctype="multipart/form-data"的表单组时,这种情况就会发生。下面是表单的HTML:

<form action="/stats" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="uploaded_file">
    <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
    <input type="submit" value="Get me the stats!" class="btn btn-default">            
  </div>
</form>

下面是如何使用multer来获取Express.js和node.js的值和名称:

var multer  = require('multer')
var upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
   // req.file is the name of your file in the form above, here 'uploaded_file'
   // req.body will hold the text fields, if there were any 
   console.log(req.file, req.body)
});

我的问题是先创建路线 要求(“。/线路/路线”)(应用); 我之前把它移到了代码末尾 app.listen 它成功了!

几分钟前我也遇到了同样的问题,我在上面的答案中尝试了所有可能的方法,但它们都有效。

我做的唯一一件事,就是升级Node JS版本,我不知道升级会影响一些东西,但它确实影响了。

我已经安装了Node JS 10.15.0版本(最新版本),我返回到8.11.3,现在一切正常。也许体解析器模块应该对此进行修复。

确保["key":" type", "value":" json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"]在你的邮差请求头中