【问题标题】:Node JS POST request returning undefined body节点 JS POST 请求返回未定义的正文
【发布时间】:2020-06-01 10:47:47
【问题描述】:

Node JS 很新,我正在尝试发布到特定的 URL 并检索数据。

我正在使用邮递员来执行此操作,但每次我向其发布响应数据时都未定义但状态码为 200。

我按照建议添加了 body-parse,但仍然没有乐趣。

我将在下面发布我的服务器代码和请求。

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 5000;

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

app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
});

app.post('/api/save-json', (req, res) => {
    console.log(req);
    res.send(
        `I received your POST request. This is what you sent me: ${req.body.json}`,
    );
});

app.listen(port, () => console.log(`Listening on port ${port}`));

我的邮递员要求是:

{
    "body" : 
    {
        "json": "some data"
    }
}

有什么想法吗?

【问题讨论】:

  • 你需要为json设置postman的headers。 Content-Type: application/json

标签: javascript node.js express post postman


【解决方案1】:

bodyreq 对象中的属性,其中包含 HTTP 请求正文(由 body-parser 设置),因为您要发送一个名为 body 的对象,您需要像这样访问它这个:req.body.body.json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 2017-08-19
    • 2021-01-05
    • 2023-04-10
    • 2014-09-23
    • 2016-02-11
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多