Home > Net >  Postman "Sending request..." forever
Postman "Sending request..." forever

Time:04-24

I am very new to node.js/express/postman so please excuse me if this question is pretty rookie. I have the following code produced from following an online tutorial. I used Postman to test it. The problem is, when I add the line app.use(express.json), Postman is unable to send the post request. It gets stuck at "Sending request...". If I exclude that one line then the "Get" requests will work. Anyone know why... based on this code. This is all of it:

Thanks!

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

CodePudding user response:

You're issue is the json middleware (app.use(express.json);), which requires you to return valid JSON (Content-Type: application/json).

I got your sample running, by updating it to the following:

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

Here's a working version: https://pastebin.com/06H6LCD2

CodePudding user response:

Try:

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