Express.js can't find token from header

Issue

I have a problem in my authentication.js file where for some reason it can’t access the token from the header but I have checked that I passed it on the front end. I also used postman and everything seems to work fine so I am sure that the problem is in the authentication.js file where when I try to console.log the token it’s undefined.Below is the code:

const token = localStorage.getItem("token");
const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
  const token = req.get("authorization");
  console.log(token); // Logs the token as undefined

  if (!token || token === "") {
    req.isAuth = false;
    return next();
  }

  try {
    let decoded = jwt.verify(token, process.env.JWT_SECRET);

    req.duser = decoded.user;
    res.status(200).send("Access granted.");
  } catch (error) {
    return res.status(403).send("Token is not valid.");
  }
  req.isAuth = true;
  return next();
};

Also here is how I call the API:

const token = localStorage.getItem("token");

const { data } = await axios.post(
  "/messages", 
  {
    headers: { 
      Authorization: token 
    },
  }
);

Solution

Please change this

headers: { Authorization: token },

to this

headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },

in your api call

Do not forget to add data param as the second param. It’s your request body.

axios
  .post(
    `/messages`, 
    data,
    {
      headers: {
        "Authorization": `Bearer ${token}`, //mind the space before your token
        "Content-Type": "application/json"
      }
    }
  );

e.x. data

{
  "firstname": "Firat",
  "lastname": "Keler"
}

And then in the backend, check your token like that

const token = req.headers.authorization.split(' ')[1];

if (!token) {
  //your logic
}

Answered By – Ahmet Firat Keler

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published