【问题标题】:Express + Postman, req.body is emptyExpress + Postman,req.body 为空
【发布时间】:2016-02-15 05:17:42
【问题描述】:

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

这是我的代码,我确保在定义路由之前使用和配置正文解析器。我只将 .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");
});

这是我使用 Postman 测试这条路线的方法。

这是我收到的回复

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' }
{}

在这一点上,我非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: node.js express postman


    【解决方案1】:

    由于您将请求作为表单数据发送,因此请使用来自 expressbody-parser 的 urlencoded() 中间件。

    bodyParser = require('body-parser').urlencoded({ extended: true }); 
    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");
    });
    

    【讨论】:

      【解决方案2】:

      花了 2 天和几个小时后,我意识到我需要将 postman 更改为 JSON:Text to JSON

      1. 如果您使用的是 express 16.4 及更高版本, 确保你有:

        const express = require("express");
        require("dotenv").config({ path: "./config/.env" });
        require("./config/db");
        const app = express();
        const userRoutes = require("./routes/user.routes");
        
        app.use(express.json()); //this is the build in express body-parser 
        app.use(                //this mean we don't need to use body-parser anymore
          express.urlencoded({
            extended: true,
          })
        );    
        //routes
        app.use("/api/user", userRoutes);
        
        // connect to the server
        app.listen(process.env.PORT, () => {
          console.log(`lestening port ${process.env.PORT}`);
        });
        

      【讨论】:

        【解决方案3】:

        我想添加一个答案,因为即使我将Content-Type: multipart/form-data 添加到标题中,似乎也无法以form-data 发送工作(这在文档中被列为正确的标题类型)。我想知道是否因为在 express 中使用 BodyParser,数据必须以 JSON 原始格式输入。我发誓我之前有 form-data 工作过,唉。

        以下是我如何让req.body 不为空:

        1. 确保在“标题”选项卡中,您已设置此键值对:
        Content-Type: application/json
        

        旁注:all available header content type values 上堆栈溢出文章的有趣链接。

        1. 在“正文”选项卡中,确保选择了raw 单选按钮,并且最右侧的下拉列表中选择了JSON

        1. 现在,如果我在我的 express 应用中控制台登录 req.body,我会看到打印:

        【讨论】:

          【解决方案4】:

          试试这个

           // 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 }));
          

          【讨论】:

            【解决方案5】:

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

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

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

            我还用 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);
            });
            

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

            【讨论】:

              【解决方案6】:

              花了几个小时后,我意识到需要将 postman 中的 Raw 类型更改为 JSON

              【讨论】:

              • 万一有人看到这里,请确保您使用的是 Postman 的 JSON 而不是 Javascript 标头。我有 Javascript,但它不会工作。
              • 为我工作。谢谢!!
              • 我几乎要倾斜了,非常感谢!亲爱的邮递员开发人员,wtf?这是您需要能够管理的唯一任务……您怎么能这样隐藏它? ;(
              • 哦!这些愚蠢的错误-_-...感谢您的回答
              • 就我而言,出于某种原因,我还必须添加一个“Content-Length”标头。否则,请求不成功,尽管它与我的 curl 请求相同,但效果很好。
              【解决方案7】:

              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");
              });
              

              然后尝试使用 PostMan 将 body 设置为 raw json:

              {
                "test": "yay"
              }
              

              【讨论】:

              • 非常感谢。问题是 PostMan 我通过表单数据发送请求
              • 我需要通过form-data 发送附件以获取空正文。如何解决?
              • 这是在一个单独的包中的事实让我想知道我用于构建 API 的方法是否正确。期待大多数更新或放置请求的主体不是很自然吗?
              • 确保将Content-Type 标头也设置为application/json
              • 非常感谢。
              猜你喜欢
              • 2019-02-08
              • 2020-12-17
              • 2021-07-23
              • 2020-01-08
              • 1970-01-01
              • 2019-06-26
              • 1970-01-01
              • 2018-04-30
              • 1970-01-01
              相关资源
              最近更新 更多