【问题标题】:How to get "name" value in a response in postman如何在邮递员的响应中获取“名称”值
【发布时间】:2020-01-27 17:57:44
【问题描述】:

我正在尝试在邮递员中发出 HTTP POST 请求。在我的项目中,我使用的是 Nodejs 的 express 框架。在邮递员中,当我发布 { "name": 'course2',},在我的回复中,我只能看到它的 id {"id":2}。我想在回复中看到 id 和名称 - {"id":2,"名称":"course2"}

我用“id”和“name”硬编码了一门课程。但是,当我尝试发出 HTTP 发布请求并使用其名称和 id 创建一个新课程时,在我的响应中我只得到 id 而不是课程的名称。

index.js

const express = require('express');
const app = express();

app.use(express.json());

const courses = [{id : 1, name : 'course1'}];

app.post('/api/courses/', (req, res) => {
    const course = {
        id: courses.length + 1,
        name: req.body.name
    };
    courses.push(course);
    res.send(course);
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening on port ${port}...`));

我想查看响应中的 id 和名称 - {"id":2,"name":"course2"}

【问题讨论】:

  • 你确定 req.body.name 不是未定义的吗?因为如果是这样,您只会得到 id 作为响应。
  • 确保您在邮递员中以 JSON 格式发送数据
  • 您可能还需要在 express 服务器上使用body-parser 模块。

标签: javascript node.js api express postman


【解决方案1】:

在邮递员中以 JSON 格式发送数据,例如:

{ "name":"Petra", } 发送前选择Json格式!

【讨论】:

    【解决方案2】:

    要使此代码正常工作,您必须像在邮递员中一样选择 body raw,如附图所示。

    您应该添加这一行来处理 x-www-form-urlencoded 值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多