javascript - 在 nodejs 困惑中返回 next()

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

为什么作者做return next()而不是next()?我知道next()是为了让流程跳转到下一个中​​间件或函数,但是为什么上面的next()需要一个return呢?

最佳答案

在函数前面加上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() 并且仍然会导致重定向无论如何。

关于javascript - 在 nodejs 困惑中返回 next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629897/

相关文章:

javascript - 嵌入视频播放器播放按钮一次播放所有视频播放器

javascript - 使用开源包转换为新的类名

node.js - Inno Setup 检查外部应用程序的版本

node.js - 如何在mongoDB中存储100个 parent 中的数百万个 child

javascript - 为 promise 中的对象赋值

javascript - socket.io 在连接时发出

javascript - 如何使用asp.net mvc获取FormData对象并通过ajax提交表单数据

javascript - Highcharts : Tooltip box thousand seperator

javascript - 选择附加项目 jquery

javascript - 如何在 Node.js CRUD 应用程序的编辑表单中显示选择值