我使用邮递员在下面的服务器中发布正文{"name" : "test"}
,但为什么不起作用? res.send
无法将(course)
发送回去。
服务器运行正常,因为我可以获取具有相同网址的请求
const express = require("express");
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: "course1" },
{ id: 2, name: "course2" },
{ id: 3, name: "course3" }
];
app.get("/api/courses", (req, res) => {
res.send(courses);
});
app.post("api/courses", (req, res) => {
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});
答案 0 :(得分:0)
我已经阅读了您的代码并添加了以下内容:
api/courses
,正确的东西是/api/courses
,开头是斜杠(/)。const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: 'course1' },
{ id: 2, name: 'course2' },
{ id: 3, name: 'course3' }
];
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post('/api/courses', (req, res) => {
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});