Search code examples
node.jsexpressnpmbody-parser

Issue with body-parser


my console shows output as undefined even though tried with content type as application/json

app.js

const bodyParser = require('body-parser')
app.use('/posts', postRoute)
app.use(bodyParser.json())

models

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('Posts', PostSchema)

routes

router.post('/post', (req, res) => {

    console.log(req.body) //It displays undefined
})

Postman enter image description here

Tried to include content type in headers but coudnt display the output


Solution

  • You must use the body parser before register other middlewares, else the body parser will set req.body after your middleware executes, which is why you see it as undefined

    const bodyParser = require('body-parser')
    app.use(bodyParser.json())
    app.use('/posts', postRoute)