Search code examples
node.jsexpressauthenticationpassport.js

MERN - TypeError: Cannot destructure property 'username' of 'req.body' as it is undefined


I am trying to authenticate an user, I'm building the backend first and testing it on Insomnia, when I send the request an error saying TypeError: Cannot destructure property 'username' of 'req.body' as it is undefined. happens.

I'm using passportjs and jwt.

This is my "server.js" file: https://www.paste.org/110929

This is my code for the "/users/signin" route: https://www.paste.org/110930

My passport.js file: https://www.paste.org/110931

I would be extremely grateful of any help as this issue has got me stuck for a good while


Solution

  • You need to add body-parser to your server.js file to catch the request body

    const express = require('express')
    const bodyParser = require('body-parser')
     
    const app = express()
     
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
     
    // parse application/json
    app.use(bodyParser.json())
    

    UPDATE

    Since express 4.16.0, you can also do:

    const express = require('express')
     
    const app = express()
    
    // parse application/x-www-form-urlencoded
    app.use(express.urlencoded({ extended: false }))
         
    // parse application/json
    app.use(express.json())