Home > Back-end >  Non-empty string being converted to "falsy" value?
Non-empty string being converted to "falsy" value?

Time:08-29

I'm a beginner learning React/Express and ran into a problem. I figured out the cause of the problem but I'm still confused. Basically, when a user logs into the application, I create an access token using JsonWebToken and store it in the session storage. Then, I make a post request with axios, passing data and also passing the access token in the headers. I do this in the following function:

const addComment = () => {
    if (newComment){
      axios
      .post(`http://localhost:3001/comments/${id}`, {comment: newComment}, {headers: {accessToken: sessionStorage.getItem("accessToken")}})
      .then(response => {
        setComments(response.data);
      }).catch(error => {
        console.log(error);
      });
      setNewComment("");
    }
  }

The request is then handled in the backend, first through a middleware:

const { verify } = require("jsonwebtoken");

const validateToken = (req, res, next) => {
  const accessToken = req.header("accessToken");

  console.log(req.header("accessToken")); // correctly returns token
  console.log(typeof accessToken); // returns 'string'
  console.log(accessToken === true); // returns 'false'

  if (!accessToken) {
    return res.json({error: "User not logged in"});
  }

  try{
    const validToken = verify(accessToken, "importantSecret");

    if (validToken){
      return next();
    }

  } catch(err){
    return res.json({error: err});
  }
}

module.exports = { validateToken };

I used console.log() statements for the sake of debugging. When I log the value of accessToken to the console, I (as expected) get the following:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im9saXZlciIsImlkIjoiNjMwYWUzYjRkMmRiZmUyZGE5NDZiNmRkIiwiaWF0IjoxNjYxNzA5ODAxfQ.oVm1bIY6J5lxnaubeUh-fWWnIObmiUuL1LXjRbrW_mQ

The problem was that even though accessToken is a non-empty string, the expression accessToken === true was still evaluating to false and !accessToken was stil evaluating to true, causing the function to return an error. I now know how to fix the problem but I would really like to know why this is happening. Answers would be appreciated!

CodePudding user response:

The token is not equal to true it is equal to the token value. What you want is to check if there is a token so you would do if(token) not if(token === true).

So console.log('hi' === true) will log false because the string 'hi' does not equal true it equals 'hi'

Check how javascript equality and sameness works here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

  • Related