检查用户是否已通过身份验证的中间件功能

Middleware Function That Checks If User Is Authenticated

我有一个 Express 中间件功能,用于检查用户是否已通过身份验证。如果他们没有通过身份验证,我想向我的前端发送一些 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});
});

但是,当我尝试 return json:

时出现此错误

Cannot set headers after they are sent to client

我该怎么做?谢谢!

那是因为即使用户未通过身份验证检查,您仍在执行 next()。这会导致您在发送 401 响应后执行其他代码,这就是错误所抱怨的。

只需添加一个else:

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();
}