Express + Postman,req.body是空的

seo*_*gju 15 node.js express postman

我知道这已被多次询问,但我一直在四处寻找,但仍无法找到问题的答案.

这是我的代码,我确保在定义路由之前使用和配置主体解析器.我只使用.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");
});
Run Code Online (Sandbox Code Playgroud)

以下是我如何使用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' }
{}
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*d A 43

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

  • 为我工作。谢谢 !! (2认同)
  • 哦!!这些愚蠢的错误-_-...感谢您的回答 (2认同)

nak*_*kwa 14

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");
});
Run Code Online (Sandbox Code Playgroud)

然后尝试使用PostMan将主体设置为rawjson:

{
  "test": "yay"
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢.问题是,使用PostMan,我通过表单数据发送请求 (2认同)

twk*_*nab 5

form-data我想添加一个答案,因为即使我添加Content-Type: multipart/form-data到标头(这在文档中被列为正确的标头类型) ,发送工作似乎也遇到困难。我想知道是否因为在 Express 中使用 BodyParser,数据必须以 JSON 原始形式输入。我发誓我form-data之前就已经上班了,唉。

这是我如何能够req.body不为空的:

  1. 确保在“标题”选项卡中,您有以下键值对设置:
Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)

将 Content-Type 设置为 application/json

旁注:有关所有可用标头内容类型值的堆栈溢出文章的有趣链接。

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

选择原始和 JSON

  1. 现在,如果我通过控制台登录req.body我的 Express 应用程序,我会看到打印的内容:

在此输入图像描述