我对诺德很陌生.js/express/postman所以如果这个问题是新手,请原谅.我有以下代码是根据在线教程生成的.我用postman 来测试.问题是,当我添加第app.use(express.json)
行时,postman 无法发送post请求.它被困在"发送请求…".如果我排除了这一行,那么"Get"请求将起作用.谁知道为什么...基于这个代码.这就是全部:
谢谢
const Joi = require('joi'); // Put required modules at the top
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('/', (req, res) => {
res.send('Hello world!!!');
});
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post('/api/courses', (req, res) => {
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(results.error.details[0].message);
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course); // assigning the id on the server. return course to client
});
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
res.send(course);
});
app.put('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(results.error.details[0].message);
course.name = req.body.name;
res.send(course);
});
app.delete('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
const index = courses.indexOf(course);
courses.splice(index, 1);
res.send(course);
})
function validateCourse(course) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.ValidationError(course, schema);
}
// PORT
const port = 3000;
app.listen(port, () => console.log(`listening on port ${port}...`));