【发布时间】:2021-03-25 23:41:27
【问题描述】:
我正在使用验证 jwt 令牌在路由中创建一个简单的有效登录检查
在路线中:
router.post("/contacts", async function (req, res, next) {
await checkLogin(req, res, next);
res.send(userController.getContacts());
});
async function checkLogin(req, res, next) {
const loggedIn = await userController.isLoggedIn(req);
if (!loggedIn) {
res.status(401).json({ error: "You are not authorized" });
}
}
在控制器中
async function isLoggedIn(req) {
let token = req.header("authorization");
if (!token) {
return false;
}
token = token.substring(7); //remove Bearer from the beginning
return jwt.verify(token, tokenSecret, function (err, decoded) {
if (typeof decoded == "object" && decoded.email == req.body.email) {
return true;
} else {
return false;
}
});
}
使用有效和无效的令牌都可以正常工作,但使用无效的令牌我得到了这个日志
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
如果我删除 status(401),则不会显示此错误日志。为什么会发生这种情况以及如何在不触发此错误日志的情况下将 HTTP STATUS 设置为 401?
【问题讨论】: