帖子上的 req.body 为空 [英] req.body empty on posts
问题描述
突然之间,我的所有项目都发生了这种情况.
All of a sudden this has been happening to all my projects.
每当我使用 express 和 body-parser 在 nodejs 中发帖时,req.body
都是一个空对象.
Whenever I make a post in nodejs using express and body-parser req.body
is an empty object.
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 和 postman,它总是空的.
Via ajax and postman it's always empty.
但是通过 curl
$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/
它按预期工作.
我尝试在前者中手动设置 Content-type : application/json
但我总是收到 400 bad request
I tried manually setting Content-type : application/json
in the former but I then always get 400 bad request
这让我发疯了.
我以为是 body-parser 更新了一些东西,但我降级了,它没有帮助.
I thought it was that something updated in body-parser but I downgraded and it didn't help.
感谢任何帮助,谢谢.
推荐答案
在 Postman 的 3 个可用于内容类型的选项中选择X-www-form-urlencoded";它应该可以工作.
In Postman of the 3 options available for content type select "X-www-form-urlencoded" and it should work.
还要去掉错误信息替换:
Also to get rid of error message replace:
app.use(bodyParser.urlencoded())
与:
app.use(bodyParser.urlencoded({
extended: true
}));
见https://github.com/expressjs/body-parser
'body-parser' 中间件只处理 JSON 和 urlencoded 数据,不处理多部分
The 'body-parser' middleware only handles JSON and urlencoded data, not multipart
正如@SujeetAgrahari 提到的,body-parser 现在内置于 express.js.
As @SujeetAgrahari mentioned, body-parser is now inbuilt with express.js.
使用 app.use(express.json());
在 JSON 正文的最新版本中实现它.对于 URL 编码的正文(由 HTTP 表单 POST 生成的那种)使用 app.use(express.urlencoded());
Use app.use(express.json());
to implement it in recent versions for JSON bodies. For URL encoded bodies (the kind produced by HTTP form POSTs) use app.use(express.urlencoded());
这篇关于帖子上的 req.body 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!