小编典典

req.body帖子为空

node.js

突然,这已经发生在我所有的项目中。

每当我使用express和body-parser在nodejs中发帖时,它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 -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/

它按预期工作。

我尝试Content-type : application/json在前者中手动设置,但随后我总是得到400 bad request

这让我发疯。

我以为是人体分析器中有一些更新,但是我降级了,但没有帮助。

任何帮助表示赞赏,谢谢。


阅读 251

收藏
2020-07-07

共1个答案

小编典典

在可用于内容类型的3个选项的邮递员中,选择“ X-www-form-urlencoded”,它应该可以工作。

另外,为了消除错误消息,请替换:

app.use(bodyParser.urlencoded())

带有:

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

参见https://github.com/expressjs/body-
parser

“ body-parser”中间件仅处理JSON和urlencoded数据,而不是多部分

2020-07-07