Node.js 检查用户是否经过身份验证的中间件功能

Node.js 检查用户是否经过身份验证的中间件功能,node.js,express,middleware,Node.js,Express,Middleware,我有一个快速中间件功能,它检查用户是否经过身份验证。如果它们没有经过身份验证,我想向我的前端发送一些JSON,说明这一点,但如果它们经过身份验证,我想在这条路径上继续我的正常功能 比如说, const checkAuth = (req, res, next) => { if (!authenticated){ res.status(401).send("You are not authorized to view this content");

我有一个快速中间件功能,它检查用户是否经过身份验证。如果它们没有经过身份验证,我想向我的前端发送一些JSON,说明这一点,但如果它们经过身份验证,我想在这条路径上继续我的正常功能

比如说,

const checkAuth = (req, res, next) => {
    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
    }
    next();
}


app.get('/protectedRoute', checkAuth, (req, res) => {
    // SOME OTHER DATABASE STUFF HERE WHICH RESULTS IN VARIABLE "data"
    res.json({msg: data});
});
但是,我在尝试返回json时遇到了以下错误:

发送到客户端后无法设置标题


我该怎么做?谢谢

这是因为即使用户身份验证检查失败,您仍在执行
next()
。这会导致您在发送
401
响应后执行额外的代码,这正是错误所抱怨的

只需添加一个

const checkAuth = (req, res, next) => {
    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
    }
    else {
        next();
    }
}
或者,有些人更喜欢使用
return
来中断流程:

    if (!authenticated){
        res.status(401).send("You are not authorized to view this content");
        return;
    }
    next();

当检测到请求未通过身份验证时停止请求

if true
块中添加
return
关键字

const checkAuth = (req, res, next) => {
    if (!authenticated){
        return res.status(401).send("You are not authorized to view this content");
    }
    next();
}