【问题标题】:How to call Connect middleware directly?如何直接调用Connect中间件?
【发布时间】:2012-12-25 10:10:24
【问题描述】:

我有一条这样的快速路线:

app.get('/', auth.authOrDie, function(req, res) {
    res.send();
});

authOrDie 函数是这样定义的(在我的auth.js 模块中):

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.send(403);
    }
});

现在,当用户未通过身份验证时,我想验证 http 请求是否具有 Authorization (Basic) 标头。为此,我想使用出色的连接中间件basicAuth()

如您所知,Express 建立在 Connect 之上,因此我可以使用 express.basicAuth

basicAuth 一般是这样使用的:

app.get('/', express.basicAuth(function(username, password) {
    // username && password verification...
}), function(req, res) {
    res.send();
});

但是,我想在我的 authOrDie 函数中使用它:

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else if {
        // express.basicAuth ??? ******
    } else {
        res.send(403);
    }
});

******我怎样才能调用具有良好参数的basicAuth函数(req?res?next?...)。

谢谢。

【问题讨论】:

    标签: node.js connect express


    【解决方案1】:

    调用express.basicAuth 函数会返回要调用的中间件函数,因此您可以像这样直接调用它:

    exports.authOrDie = function(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {
            return express.basicAuth(function(username, password) {
                // username && password verification...
            })(req, res, next);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-02-04
      • 1970-01-01
      • 2014-05-08
      • 2014-10-14
      • 2011-07-15
      • 2012-06-08
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多