node.js 快递+邮递员,req.body为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33695893/
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 19:31:56  来源:igfitidea点击:

Express + Postman, req.body is empty

node.jsexpresspostman

提问by seongju

I know this has been asked multiple times, but I have been looking around and still can't find an answer to my problem.

我知道这已被多次询问,但我一直在环顾四周,仍然找不到我的问题的答案。

Here is my code, I make sure to use and configure body parser before defining the routes. I'm only using .json() with bodyParser because right now I'm only testing a POST function, but I've even tried with app.use(bodyParser.urlencoded({ extended: true }));

这是我的代码,我确保在定义路由之前使用和配置正文解析器。我只使用 .json() 和 bodyParser 因为现在我只测试一个 POST 函数,但我什至尝试过 app.use(bodyParser.urlencoded({extended: true }));

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

app.use(bodyParser.json());
app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function() {
    console.log("Node app is running at localhost:" + app.get('port'))
});

app.post('/itemSearch', function(req, res) {
    //var Keywords = req.body.Keywords;
    console.log("Yoooooo");
    console.log(req.headers);
    console.log(req.body);
    res.status(200).send("yay");
});

Here is how I use Postman to test this route. enter image description here

下面是我如何使用 Postman 来测试这条路线。 在此处输入图片说明

and here is the response I receive

这是我收到的回复

Node app is running at localhost:5000
Yoooooo
{ host: 'localhost:5000',
  connection: 'keep-alive',
  'content-length': '146',
  'cache-control': 'no-cache',
  origin: 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
  'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarynJtRFnukjOQDaHgU',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
  'postman-token': '984b101b-7780-5d6e-5a24-ad2c89b492fc',
  accept: '*/*',
  'accept-encoding': 'gzip, deflate',
  'accept-language': 'en-GB,en-US;q=0.8,en;q=0.6' }
{}

At this point I would really appreciate any help. Thanks.

在这一点上,我真的很感激任何帮助。谢谢。

采纳答案by nakwa

AFAIK you need to use the Body-Parser : https://github.com/expressjs/body-parser

AFAIK 你需要使用 Body-Parser :https: //github.com/expressjs/body-parser

bodyParser = require('body-parser').json();
app.post('/itemSearch', bodyParser, function(req, res) {
  //var Keywords = req.body.Keywords;
  console.log("Yoooooo");
  console.log(req.headers);
  console.log(req.body);
  res.status(200).send("yay");
});

Then try with PostMan setting the body as rawjson:

然后尝试使用 PostMan 将正文设置为rawjson:

{
  "test": "yay"
}

回答by David A

After spending a few hours I realized need to change the Raw type in postman to JSONenter image description here

花了几个小时后,我意识到需要将邮递员中的原始类型更改为 JSON在此处输入图片说明

回答by Nankai

Try this

尝试这个

 // create application/json parser
    app.use(bodyParser.json());
    // parse various different custom JSON types as JSON
    app.use(bodyParser.json({ type: 'application/*+json' }));
    // parse some custom thing into a Buffer
    app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
    // parse an HTML body into a string
    app.use(bodyParser.text({ type: 'text/html' }));
    // parse an text body into a string
    app.use(bodyParser.text({ type: 'text/plain' }));
    // create application/x-www-form-urlencoded parser
    app.use(bodyParser.urlencoded({ extended: false }));

回答by Teguh Suryo Santoso

In my case, I solve it By Adding "type":"text"to urlencodeditem int the exported collection jsonfile generated by postman. I observe it because there are some of my request is successfully done. The difference is the missing typefield in the json generated postman collection file. This problem also happen to my teammate.

就我而言,我通过将邮递员生成的导出集合文件添加"type":"text"urlencodeditem int来解决它json。我观察它是因为我的一些请求被成功地完成了。不同的是typejson生成的邮递员集合文件中缺少字段。这个问题也发生在我的队友身上。

before (failed request): "body": { "mode": "urlencoded", "urlencoded": [ { "key": "email", "value": "{{userEmail}}" }, { "key": "password", "value": "{{userPassword}}" } ] }

之前(失败的请求): "body": { "mode": "urlencoded", "urlencoded": [ { "key": "email", "value": "{{userEmail}}" }, { "key": "password", "value": "{{userPassword}}" } ] }

after (successful request): "body": { "mode": "urlencoded", "urlencoded": [ { "key": "email", "value": "{{userEmail}}", "type": "text" }, { "key": "password", "value": "{{userPassword}}", "type": "text" } ] }

之后(成功请求): "body": { "mode": "urlencoded", "urlencoded": [ { "key": "email", "value": "{{userEmail}}", "type": "text" }, { "key": "password", "value": "{{userPassword}}", "type": "text" } ] }

I also write parser script in javascript language to handle it.

我还用 javascript 语言编写解析器脚本来处理它。

const fs = require('fs');
let object = require(process.argv[2]);

function parse(obj) {
    if(typeof obj === 'string') return;
    for(let key in obj) {
        if(obj.hasOwnProperty(key)) {
            if(key === 'urlencoded') {
                let body = obj[key];
                for(let i = 0;i < body.length;i++) {
                    body[i].type = "text";
                }
            }
            else parse(obj[key]);
        }
    }
}

parse(object);
fs.writeFile('ParsedCollection.json', JSON.stringify(object, null, '\t'), function(err){
    //console.log(err);
});

Just run it in terminal node parser.js <json postman collection file path>and it will output in ParsedCollection.jsonfile. After that import this file into postman.

只需在终端中运行它,node parser.js <json postman collection file path>它就会在ParsedCollection.json文件中输出。之后,将此文件导入邮递员。