jwtexpress-jwt

UnauthorizedError: No authorization token was found


In our backend routes/index.js, we have

var auth = jwt({ secret: process.env.JWT_SECRET_KEY, userProperty: 'payload' });

... ...

router.get('/ask', auth, function (req, res, next) {

    ... ...
}

I tried to test the /ask api from the frontend to backend in localhost. Here is a part of the code in the frontend:

async handleButtonClicked() {
    cost data: any = {}
    const token = await getSignToken();
    console.log(token);
    const headers = { Authorization: 'Bearer ' + token };
    await axios.get("https://localhost:3000/ask", data, { headers, withCredentials: true });
}

I then signed in the frontend webpage in localhost, then launched the above function. I did see the token printed in the console of dev tools of the frontend. And in the console of the backend, it showed that the api was called. But it raised an error UnauthorizedError: No authorization token was found.

Could anyone tell me what might be the reason? How could I debug?

Additionally, I have a doubt about the value of process.env.JWT_SECRET_KEY. I see somewhere in our code it is just JWT_SECRET_KEY, somewhere in the production its a encrypted complex string. I would like to know if this secret is important (or maybe the reason of UnauthorizedError: No authorization token was found?). Should we always have the same secret in localhost and production?

PS: I cannot find Authorization in the headers of the /ask request from the frontend.

enter image description here


Solution

  • await axios.get("https://localhost:3000/ask", data, { headers, withCredentials: true });

    should be

    await axios.post("https://localhost:3000/ask", data, { headers, withCredentials: true });