在nodejs混淆中返回next()

Nic*_*ler 6 javascript node.js

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js

function isAuthenticated (req, res, next) {
    // if user is authenticated in the session, call the next() to call the next request handler 
    // Passport adds this method to request object. A middleware is allowed to add properties to
    // request and response objects

    //allow all get request methods
    if(req.method === "GET"){
        return next();
    }
    if (req.isAuthenticated()){
        return next();
    }

    // if the user is not authenticated then redirect him to the login page
    return res.redirect('/#login');
};
Run Code Online (Sandbox Code Playgroud)

为什么作者return next()而不是next()?我知道next()是让流量跳转到下一个中间件或功能,但为什么它需要returnnext()以上?

Num*_*ock 2

惯例是在函数前面加上 areturn来退出该函数。另一种选择是使用if-else if-else而不是仅仅使用if. 在这种情况下,您只想退出该函数并在中间件链上进一步前进。

您会经常看到这种模式。例如,这很常见:

someFunction(function(err, result) {
    if (err) {
        return console.error(err);
    }

    console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

与此相比,它的嵌套更少,并且对大多数人来说更容易阅读:

someFunction(function(err, result) {
    if (err) {
        console.error(err);
    } else {
        console.log(result);
    }
});
Run Code Online (Sandbox Code Playgroud)

第一种模式还可以防止您意外调用next()两次甚至多次,以防您的if-else逻辑出现错误。在您发布的情况下,这正是不应该发生的情况。next()在任何情况下,它都可以调用next()并仍然导致重定向。