问题描述
我知道这个问题已被问过多次,但提供的解决方案对我不起作用。
我有一个受保护的路径来查找用户。请求由 authenticate
中间件验证,它基本上检查用户的 cookie 是否有效,然后调用路由 getUser
。当我不使用中间件时,该路由运行良好,因此问题可能来自 authenticate
。
我已按照建议使用了 return res.status(200).json({})
。
在使用 cookie 测试路由时,chai 进行了两次调用。第一个成功了,但是一旦路由被命中,就会进行另一个调用,没有任何 cookie。奇怪的。在邮递员中,同样的事情。它在没有 authenticate
的情况下工作得很好,但它会返回 unauthorized
。在终端中,错误是:
[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头
这是 authenticate
中间件和路由:
// router
const router = express.Router();
router.get("/user/:id",authenticate,getUser);
// authenticate
const authenticate = (req: Authenticate,res: Response,next: NextFunction) => {
const { mycookie } = req.cookies;
if (mycookie) {
jwt.verify(mycookie,process.env.JWT_TOKEN_KEY,(error,parsedToken) => {
if (error) {
return res.sendStatus(403);
}
req.cookie = { _id: parsedToken._id,locale: parsedToken.locale };
return next();
});
}
return res.sendStatus(401);
};
export default authenticate;
// the get - user/:id route
const getUser = async (
req: GetUser,res: IResponse
): Promise<IResponse> => {
try {
const user = await UserControler.findUserById(req.params.id);
return res.status(200).json({ user });
} catch (err) {
throw new Error("error.unkNown");
}
};
export default getUser;
如何解决这个问题?
解决方法
在您的 authenticate
函数中,您忘记将 else
语句添加到 if (mycookie)
。
因此将始终发送未授权,这显然是您获得未授权使用良好 cookie 的原因,然后由于已发送未授权,当 getUser 尝试发送 http 响应时将抛出您描述的错误。
将 return res.sendStatus(401);
包裹在 else
语句中,它应该可以正常工作。