如何直接调用Connect中间件?

San*_*nda 4 connect node.js express

我有这样一个快速路线:

app.get('/', auth.authOrDie, function(req, res) {
    res.send();
});
Run Code Online (Sandbox Code Playgroud)

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

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

现在,当用户未经过身份验证时,我想验证http请求是否具有授权(基本)标头.为此,我想使用伟大的连接中间件basicAuth().

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

basicAuth一般使用这样的:

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

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

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

****** 如何使用良好的参数调用basicAuth函数(req?res?next?...).

谢谢.

Joh*_*yHK 7

调用该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);
    }
});
Run Code Online (Sandbox Code Playgroud)