【问题标题】:Can't get POST data using NodeJS/ExpressJS and Postman无法使用 NodeJS/ExpressJS 和 Postman 获取 POST 数据
【发布时间】:2017-06-16 17:50:33
【问题描述】:

这是我服务器的代码:

var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());

app.post("/", function(req, res) {
    res.send(req.body);
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

从 Postman,我向 http://localhost:3000/ 发起 POST 请求,在 Body/form-data 中我有一个键“foo”和值“bar”。

但是,我在响应中不断收到一个空对象。 req.body 属性始终为空。

我错过了什么吗?

【问题讨论】:

    标签: node.js express postman body-parser


    【解决方案1】:

    添加请求的编码。这是一个例子

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

    然后在Postman中选择x-www-form-urlencoded或者将Content-Type设置为application/json并选择raw

    编辑以使用 raw

    原始

    {
      "foo": "bar"
    }
    

    标题

    Content-Type: application/json
    

    EDIT #2回答聊天中的问题:

    1. 为什么它不能与表单数据一起使用?

    你当然可以,看看这个答案How to handle FormData from express 4

    1. 使用x-www-form-urlencodedraw有什么区别

    differences in application/json and application/x-www-form-urlencoded

    【讨论】:

    • 如果我使用x-www-form-urlencoded 而不是form-data,它会起作用。但是,如果我将标头“Content-Type”设置为值为“application/json”并使用form-data,则它不起作用。知道为什么吗?
    • 如果您将content-type 设置为application/json,您可以使用raw。只需确保将密钥包装在“中。我会更新答案
    • 谢谢。你能解释一下1-为什么它不能与form-data一起工作吗? 2- 使用 x-www-form-urlencodedraw 有什么区别;在博客文章中,我没有看到bodyParser.urlencoded() 的使用,所以我想大多数人都不会使用x-www-form-urlencoded 不管那是什么?
    【解决方案2】:
    let express = require('express');
    let app = express();
    
    // For POST-Support
    let bodyParser = require('body-parser');
    let multer = require('multer');
    let upload = multer();
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.post('/api/sayHello', upload.array(), (request, response) => {
        let a = request.body.a;
        let b = request.body.b;
    
    
        let c = parseInt(a) + parseInt(b);
        response.send('Result : '+c);
        console.log('Result : '+c);
    });
    
    app.listen(3000);
    

    示例 JSON 和 JSON 的结果:

    设置 Content-typeL 应用程序/JSON:

    【讨论】:

    • 这读起来更像是一个找不同的游戏,而不是一个答案。你改变了什么?为什么要解决问题?这是否增加了 R. Gulbrandsen 在他们去年接受的答案中尚未提及的任何内容?
    • 这实际上是一个实时示例。这显然会有所帮助。
    【解决方案3】:

    我在使用路由器时遇到了这个问题。只有 GET 工作,POST、PATCH 和 delete 反映 req.body 的“未定义”。在路由器文件中使用 body-parser 后,我能够让所有 HTTP 方法正常工作......

    我是这样做的:

    ...
    const bodyParser = require('body-parser')
    ...
    router.use(bodyParser.json());
    router.use(bodyParser.urlencoded({ extended: true }));
    ...
    ...
    // for post
    router.post('/users', async (req, res) => {
        const user = await new User(req.body) // here is where I was getting req.body as undefined before using body-parser
        user.save().then(() => {
            res.status(201).send(user)
        }).catch((error) => {
            res.status(400).send(error)
        })
    })
    

    对于 PATCH 和 DELETE,user568109 建议的这个技巧也有效。

    【讨论】:

    • 这与其他答案有什么不同吗?如果有类似的答案,您本可以投票赞成
    • 如果您能解释一下您是如何使用正文解析器的,那将会很有用!另外,如果你能提供一些关于 body-parser 是什么的上下文,那就太好了。
    • Nic Sxerman,我已在我的编辑中编辑并发布了路由器代码。
    【解决方案4】:

    我想补充的是,如果您通过 Express.js 生成器创建了项目 在您的 app.js 中,它还会生成以下代码

    app.use(express.json());
    

    如果您将 body-parser 放在此代码之上,req.body 将返回 null 或 undefined 你应该把它放在上面的代码下面看下面的正确位置

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

    【讨论】:

    • 这是一样的。 Express 已内置正文解析器 app.use(express.json()); 将调用内置正文解析器。所以在 express 版本 4.16.0 之后就不需要安装 body parser
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2015-06-28
    • 2020-03-06
    相关资源
    最近更新 更多