Search code examples
javascriptnode.jsexpressexpress-jwt

TypeError: Cannot read property 'authorization' of undefined using express-jwt


I am trying to add routes authentication for that I am using express-jwt I added this middleware to protect post creation routes. But while testing I get the error in postman.

error

TypeError: Cannot read property &#39;authorization&#39; of undefined<br> &nbsp; &nbsp;at Object.getTokenFromHeaders [as getToken]

These are my code for express jwt

auth.js

import  jwt from 'express-jwt';
const getTokenFromHeaders = (req) => {
    const { headers: { authorization } } = req;
    console.log(authorization);     <----- in this log i am getting token
    if(authorization && authorization.split(' ')[0] === 'Token') {
        return authorization.split(' ')[1];

    }
    return null;
};

const auth = {
    required: jwt({
        secret: 'secret',
        userProperty: 'payload',
        getToken: getTokenFromHeaders,
    }),
    optional: jwt({
        secret: 'secret',
        userProperty: 'payload',
        getToken: getTokenFromHeaders,
        credentialsRequired: false,
    }),
};

module.exports = auth;

routes.js

routes.post('/post', auth.required, postController.post);


Solution

  • You have an error on this line:

    const { headers: { authorization } } = req.body;
    

    Because headers prop is on req object, not on req.body, so it should be like this instead:

    const { headers: { authorization } } = req;