node.js 帖子上的 req.body 为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24543847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:35:43  来源:igfitidea点击:

req.body empty on posts

node.jsexpress

提问by Joseph Dailey

All of a sudden this has been happening to all my projects.

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

Whenever I make a post in nodejs using express and body-parser req.bodyis an empty object.

每当我使用 express 在 nodejs 中发帖时,body-parserreq.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);
});

Via ajax and postman it's always empty.

通过 ajax 和 postman,它总是空的。

However via curl

但是通过 curl

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

it works as intended.

它按预期工作。

I tried manually setting Content-type : application/jsonin the former but I then always get 400 bad request

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

This has been driving me crazy.

这让我发疯了。

I thought it was that something updated in body-parser but I downgraded and it didn't help.

我以为是 body-parser 更新了一些东西,但我降级了,它没有帮助。

Any help appreciated, thanks.

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

回答by Mick Cullen

In Postman of the 3 options available for content type select "X-www-form-urlencoded" and it should work.

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

Also to get rid of error message replace:

还要摆脱错误消息替换:

app.use(bodyParser.urlencoded())

With:

和:

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

See https://github.com/expressjs/body-parser

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

The 'body-parser' middleware only handles JSON and urlencoded data, not multipart

'body-parser' 中间件只处理 JSON 和 urlencoded 数据,而不是 multipart

回答by sirthud

With Postman, to test HTTP post actions with a raw JSON data payload, select the rawoption and set the following header parameters:

使用 Postman,要使用原始 JSON 数据负载测试 HTTP 发布操作,请选择该raw选项并设置以下标头参数:

Content-Type: application/json

Also, be sure to wrap any strings used as keys/values in your JSON payload in double quotes.

此外,请务必将用作 JSON 有效负载中的键/值的任何字符串用双引号括起来。

The body-parserpackage will parse multi-line raw JSON payloads just fine.

body-parser包将很好地解析多行原始 JSON 有效负载。

{
    "foo": "bar"
}

Tested in Chrome v37 and v41 with the Postman v0.8.4.13 extension (body-parserv1.12.2 and expressv4.12.3) with the setup below:

使用 Postman v0.8.4.13 扩展(body-parserv1.12.2 和expressv4.12.3)在 Chrome v37 和 v41 中测试,设置如下:

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

// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// ... Your routes and methods here

Postman raw json payload

邮递员原始 json 有效负载

回答by Jason Kim

I made a really dumb mistake and forgot to define nameattributes for inputs in my html file.

我犯了一个非常愚蠢的错误,忘记name在我的 html 文件中定义输入的属性。

So instead of

所以代替

<input type="password" class="form-control" id="password">

I have this.

我有这个。

<input type="password" class="form-control" id="password" name="password">

Now request.bodyis populated like this: { password: 'hhiiii' }

现在request.body填充如下:{ password: 'hhiiii' }

回答by Xan-Kun Clark-Davis

I discovered, that it works when sending with content type

我发现,它在使用内容类型发送时有效

"application/json"

“应用程序/json”

in combination with server-side

结合服务器端

app.use(bodyParser.json());

app.use(bodyParser.json());

Now I can send via

现在我可以通过

var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);

and the result is available in request.body.nameon the server.

结果request.body.name在服务器上可用。

回答by stone

I ran into this problem today, and what fixed it was to remove the content-type headerin Postman! Very strange. Adding it here in case it helps someone.

我今天遇到了这个问题,解决方法是删除Postman中的 content-type 标头!很奇怪。在这里添加它以防它对某人有帮助。

I was following the BeerLocker tutorial here: http://scottksmith.com/blog/2014/05/29/beer-locker-building-a-restful-api-with-node-passport/

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

回答by Tuan

You have to check whether the body-parser middleware is set properly to the type of request(json, urlencoded).

您必须检查 body-parser 中间件是否正确设置为请求类型(json,urlencoded)。

If you have set,

如果你已经设置,

app.use(bodyParser.json());

then in postman you have to send the data as raw.

然后在邮递员中,您必须将数据作为原始数据发送。

https://i.stack.imgur.com/k9IdQ.pngpostman screenshot

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

If you have set,

如果你已经设置,

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

then 'x-www-form-urlencoded' option should be selected.

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

回答by fiat

My problem was I was creating the route first

我的问题是我首先创建了路线

// ...
router.get('/post/data', myController.postHandler);
// ...

and registering the middleware afterthe route

并在路由之后注册中间件

app.use(bodyParser.json());
//etc

due to app structure & copy and pasting the project together from examples.

由于应用程序结构和从示例中复制和粘贴项目。

Once I fixed the order to register middleware before the route, it all worked.

一旦我在路由之前修复了注册中间件的顺序,一切都奏效了。

回答by Shaggie

Even when i was learning node.js for the first time where i started learning it over web-app, i was having all these things done in well manner in my form, still i was not able to receive values in post request. After long debugging, i came to know that in the form i have provided enctype="multipart/form-data"due to which i was not able to get values. I simply removed it and it worked for me.

即使当我第一次学习 node.js 时,我开始通过 web 应用程序学习它,我已经在我的表单中以良好的方式完成了所有这些事情,但我仍然无法在 post 请求中接收值。经过长时间的调试,我开始知道在我提供的表单中我enctype="multipart/form-data"无法获得值。我只是删除了它,它对我有用。

回答by Mohammad Haque

It seems if you do not use any encType (default is application/x-www-form-urlencoded) then you do get text input fields but you wouldn't get file.

似乎如果您不使用任何 encType (默认为application/x-www-form-urlencoded),那么您确实会获得文本输入字段,但不会获得文件。

If you have a form where you want to post text input and file then use multipart/form-dataencoding type and in addition to that use multermiddleware. Multer will parse the request object and prepare req.filefor you and all other inputs fields will be available through req.body.

如果您有一个表单,要在其中发布文本输入和文件,则使用multipart/form-data编码类型,此外还使用multer中间件。Multer 将解析请求对象并req.file为您准备,所有其他输入字段将通过req.body.

回答by vpage

Make sure ["key" : "type", "value" : "json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"] is in your postman request headers

确保 ["key" : "type", "value" : "json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"] 在您的邮递员请求标头