Stack Exchange
req.headers('Authorization') is undefined
I'm having trouble with this code because token is returning undefined.
In my frontend:
export const fetchUser = async (token: any) => {
        const res = await axios.post('/user/getuser', {
            headers: {Authorization : token}
        });
        return res;
};

And in my middleware is:
const jwt = require('jsonwebtoken');
import {Request, Response, NextFunction} from 'express';

const auth = (req: Request | any, res: Response, next: NextFunction) => {
    try {
        const token = req.headers('Authorization');
        console.log(token);
        if(!token) return res.status(400).json({msg: 'Invalid Authentication.'});

        jwt.verify(token, process.env.ACCESS_TOKEN as string, (err: any, user: any) => {
            if(err) return res.status(400).json({msg: "Invalid Authentication token"})

            req.user = user;

            next();

        });
    } catch (error: any) {
        return res.status(500).json({msg: error.message});
    }
}
module.exports = auth;

I've tested it in Postman and there's no problem, however there's a problem when I make requests from my frontend.

Can you check the request from network tab in dev tools and confirm whether Authorization header exists under request headers.

You aren't passing a token to the fetchUser function. Why you aren't passing a token (or are passing undefined) to the fetchUser function is your real problem.

I am passing a token in the fetchUser, I console.log the token before passing it and the token exists. However, in the auth middleware, I tried to console log the token being passed and then it returns undefined. I have solved the problem by accessing the token in the middleware as req.body.headers.Authorization because the header isn't working. :-D

You can try using
req.headers.authorization

This way you can get the auth object from the request header and get the value from it.
I did the as above and it worked well with no problem, try that please. I

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
