【发布时间】: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