Home > database >  Express JS req.body undefined
Express JS req.body undefined

Time:12-04

req.body returns undefined. Here is my code.

const express = require('express');

const app = express();

const courses = [
    { id: 1, name: 'course1'},
    { id: 2, name: 'course2'},
    { id: 3, name: 'course3'},
];

app.use(express.json());

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


const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening on port ${port}...`))

Using postman to post an object, for example

{ 
    "name" : "newCourse"
}

will return only id, not returning both the expected id and name. Console.log(course.name) returns undefined. This code is from a tutorial by Programming with Mosh https://www.youtube.com/watch?v=pKd0Rpw7O48 Time: 33 min I'm a beginner in node and express, any clue and explaination on why this doesn't work as it did in the tutorial?

CodePudding user response:

From the documentation:

req.body: Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

CodePudding user response:

Add this line app.use(express.urlencoded({})) below app.use(express.json()) line

  • Related