在nodejs混乱中返回next()



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

为什么作者使用return next()而不是next()?我知道next()是让流跳到下一个中间件或功能,但为什么它需要return来代替上面的next()

惯例是预先准备一个return以退出函数。另一种选择是使用if-else if-else而不是仅使用if。在这种情况下,您只想退出该函数,并在中间件链上更进一步。

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

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

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

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

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

最新更新