I got caught on this error so I hope you can help me.
I am trying to validate the JWT (JSON Web Token) before I process the information so I can avoid if the token is invalid, if it doesn't exist, if it's expired or if it was used already.
Everything works fine but i got this warning on console
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
here is my code
try {
const token = req.header("Authorization")
if (!token)
return res.formatter.unauthorized("No existe el token");
let verified = {}
jwt.verify(getAccessToken(token), process.env.JWT_SECRET, (err, verifiedJWT) => {
if(err){
if(err.message === "jwt expired"){
return res.formatter.unauthorized('Token expired');
}
}else{
verified = verifiedJWT;
}
});
if (!verified)
return res.formatter.unauthorized("Invalid token");
const tokenInvalid = await TokensInvalid.findOne({ tokenInvalid: token });
if (tokenInvalid)
return res.formatter.unauthorized('Token already used');
req.token = token;
req.user = verified.user;
next();
} catch (err) {
return res.formatter.serverError(err.message)
}
};```
Hope you can support me. Thank you all!
You need to move your code inside the jwt.verify()
callback. It is non-blocking and asynchronous so the code after it will execute before the callback, not after. To fix, move that code inside the callback itself:
But, even better since you're already using await
in this function is to use a promisified version of jwt.verify()
.
const { promisify } = require('util');
jwt.verifyP = promisify(jwt.verify);
try {
const token = req.header("Authorization")
if (!token)
return res.formatter.unauthorized("No existe el token");
// see if this token is verified
let verified = await jwt.verifyP(getAccessToken(token), process.env.JWT_SECRET);
if (!verified) {
return res.formatter.unauthorized("Invalid token");
}
} catch (err) {
// decide which jwt error to send
if (e.message === "jwt expired") {
res.formatter.unauthorized('Token expired');
} else {
res.formatter.unauthorized("Invalid token");
}
return;
}
try {
// check if token is in database as an invalid one
const tokenInvalid = await TokensInvalid.findOne({ tokenInvalid: token });
if (tokenInvalid) {
return res.formatter.unauthorized('Token already used');
}
req.token = token;
req.user = verified.user;
next();
return;
} catch (err) {
return res.formatter.serverError(err.message)
}
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.