永远的邮递员"Sending request..."

Postman "Sending request..." forever

我是 node 的新手。js/express/postman 如果这个问题是菜鸟问题,请原谅。我根据在线教程生成了以下代码。我用邮差来测试它。问题是,当我添加行 app.use(express.json) 时,Postman 无法发送 post 请求。它卡在“发送请求...”。如果我排除那一行,那么“获取”请求将起作用。任何人都知道为什么......基于这段代码。这就是全部:

谢谢!

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}...`));

您遇到的问题是 json 中间件 (app.use(express.json);),它要求您 return 有效 JSON (Content-Type: application/json)。

我得到了你的示例 运行,将其更新为以下内容:

app.get('/', (req, res) => {
    res.json({msg: 'Hello world!!!'});
});

这是一个工作版本:https://pastebin.com/06H6LCD2

尝试:

app.use(express.json({ extended: false }));