首页 文章

无法使用 NodeJS/ExpressJS 和 Postman 获取 POST 数据

提问于
浏览
8

这是我服务器的代码:

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属性始终为空。

我错过了什么?
在此输入图像描述

3 回答

  • 20

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

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

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

    编辑以使用原始

    {
      "foo": "bar"
    }
    

    Content-Type: application/json
    

    编辑#2回答聊天中的问题:

    • 为什么它不能与 form-data 一起使用?

    你确定可以,只看这个答案如何从 express 4 处理 FormData

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

    application/json 和 application/x-www-form-urlencoded 的差异

  • 1
    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 的结果:

    示例 Json 和 json 的结果

    设置 Content-typeL application/JSON:

    设置 Content-type:application/json

  • 0

    我在使用路由器时遇到了这个问题。只有 GET 正在工作,POST,PATCH 和删除反映了 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 建议的这个技巧也奏效了。

相关问题