Hi,
in order to consolidate my acquired knowledge in node, express and mongo, I started to build an app. So I took part of the authentication method of this news post:
I am using this code from the post:
const jwt = require("jsonwebtoken");
module.exports = async (request, response, next) => {
try {
// get the token from the authorization header
const token = await request.headers.authorization.split(" ")[1];
//check if the token matches the supposed origin
const decodedToken = await jwt.verify(token, "RANDOM-TOKEN");
// retrieve the user details of the logged in user
const user = await decodedToken;
// pass the user down to the endpoints here
request.user = user;
// pass down functionality to the endpoint
next();
} catch (error) {
response.status(401).json({
error: new Error("Invalid request!"),
});
}
};
I am having some problems with the app when I try to access the rutes they need to have the authentication, so testing with console.logs I got stack when I want to log what is on “decodedToken” constant, in the auth.js file (which is the code I copied above). It seems the code is stacked there. What can it be?
Thank you in advance!
Yes, exactly that’s what I read too, and I tried to do it without the await, and it was still stacked
I have it on github in case anyone would like to spend some time helping me look for what might be
But anyways, when I console.log(token), it returns the correct token, and I am doing the jwt.sign in this way, so “RANDOM-TOKEN” should not be a problem either if I am right:
I assume you are testing it using Postman or something similar? Are you adding the bearer token correctly and do you get the token back from this code?
Yes, exactly when I try it with Postman, and I console log the “request.headers.authorization” I get the bearer + the token. So when I console log the token I get only the token after spliting it
Try moving the custom CORS middleware to the top of the file as the very first thing after the dependencies (starter repo code). Or remove it a use the cors package instead, still keeping it at the top of the file.
Did you use the starter repo?
Why is your DB code commented out and why did you add other packages?