Express + Postman,req.body为空。

30

我知道这个问题已经被问过多次了,但是我已经找了很久,仍然找不到解决方案。

这里是我的代码,我确保在定义路由之前使用和配置了body-parser。我只使用.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' }
{}

目前我真的非常需要帮助。谢谢。

8个回答

106

花了几个小时后,我意识到需要在postman中将Raw类型更改为JSON输入图像描述


1
以防万一,确定你正在使用Postman的JSON头,而不是Javascript头。我之前使用了Javascript头,但它无法工作。 - k00k
2
对我有用。谢谢!! - Rajan Patil
我差点就要崩溃了,非常感谢!亲爱的Postman开发人员们,这是你们唯一需要能够处理的任务...你们怎么会把它隐藏起来呢?;( - ant45de
3
哦!这些愚蠢的错误-_-... 感谢答案。 - Suraj Kumar
1
在我的情况下,由于某些原因,我还不得不添加一个“Content-Length”标头。否则,请求不成功,尽管它与我的curl请求相同,而该请求正常工作。 - Dievskiy
谢谢你救了我的命... - Muhammed Jaseem

28

据我所知,您需要使用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"
}

2
非常感谢。问题在于我使用PostMan通过表单数据发送请求。 - seongju
1
我需要通过 form-data 发送附件,但是得到了空的正文。如何解决? - 151291
这个在一个单独的包中的事实让我想知道我为构建API所采取的方法是否正确。难道不是自然而然地期望大多数更新或放置请求都有主体吗? - Brady Dowling
请确保您设置了Content-Type头为application/json - Scott

4

我想要添加一个答案,因为似乎有困难将请求以form-data的形式发送,在我的Header中加入了Content-Type: multipart/form-data(文档中列出了此正确的header类型),但仍然无法正常工作。我想知道是否因为在express中使用了BodyParser,数据必须以JSON的原始格式传入。我发誓之前已经让form-data正常工作过,可惜现在不行了。

以下是我如何使得req.body不为空的方法:

  1. 确保在“Headers”选项卡中,您设置了这个键值对:
Content-Type: application/json

将Content-Type设置为application/json

顺便提一下:有趣的链接到stackoverflow文章,其中列出了所有可用的头部内容类型值.

  1. 在"Body"选项卡中,请确保选择了"raw"单选按钮,并选择最右边的下拉列表中的"JSON":

选择raw和JSON

  1. 现在如果我在我的express应用程序中记录控制台日志req.body,我会看到打印出来的内容:

输入图像描述


2

试试这个

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

2

花了2天时间,我意识到需要将Postman中的文本转换为JSON格式。

  1. If you're using express 16.4 and up, make sure you have :

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

0
在我的情况下,我通过在postman生成的导出集合的json文件中,将 urlencoded 项中的"type":"text"添加到其中来解决它。我观察到这一点是因为我的某些请求已经成功完成了。不同之处在于,在postman集合文件中生成的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 <json postman collection file path>,它将输出到ParsedCollection.json文件中。然后将此文件导入到postman中。


0

由于您正在以表单数据的形式发送请求,请使用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");
});

-1

你好,你不需要使用body parser

const StringDecoder = require("string_decoder").StringDecoder;

 _server.post("/users", function (req, res) {
    const decoder = new StringDecoder();
    let buffer = "";
    req.on("data", function (data) {
      buffer += decoder.write(data);
    });
    req.on("end", function () {
      try {
        console.log(JSON.parse(buffer));
        res.json({ success: "ok });
      } catch (e) {
        console.log(e);
      }
    });
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接