简体   繁体   中英

Express.js can't find token from header

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

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/

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

ex 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM