Home > Back-end >  Express.js can't find token from header
Express.js can't find token from header

Time:08-12

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 },
      });

CodePudding user response:

may be that your token isnt a Base64 String via client-side. Hope this helps

const temp = localStorage.getItem("token");
const token = Buffer.from(tmp, 'utf8').toString('base64')
axios.post('/messages', {
  headers: {
    'Authorization': `Basic ${token}`
  }
});

RESOURCE: https://flaviocopes.com/axios-send-authorization-header/

CodePudding user response:

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
}
  • Related