简化此 node.js 函数的调用方式

Simplify how this node.js function is called

我正在使用 node.js restify。

下面的代码工作正常。

var server = restify.createServer({
    name: 'myapp',
    version: '1.0.0'
});

server.use(function (req, res, next) {
    var users;

    // if (/* some condition determining whether the resource requires authentication */) {
    //    return next();
    // }

    users = {
        foo: {
            id: 1,
            password: 'bar'
        }
    };

    // Ensure that user is not anonymous; and
    // That user exists; and
    // That user password matches the record in the database.
    if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
        // Respond with { code: 'NotAuthorized', message: '' }
        next(new restify.NotAuthorizedError());
    } else {
        next();
    }

    next();
});

我想要的是转换 server.use(function (req, res, next) { ... 中的函数代码块,以便我可以这样调用函数 server.use(verifyAuthorizedUser(req, res, next));

所以,我所做的就是创建这个函数;

function verifyAuthorizedUser(req, res, next)
{
    var users;

    // if (/* some condition determining whether the resource requires authentication */) {
    //    return next();
    // }

    users = {
        foo: {
            id: 1,
            password: 'bar'
        }
    };

    // Ensure that user is not anonymous; and
    // That user exists; and
    // That user password matches the record in the database.
    if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
        // Respond with { code: 'NotAuthorized', message: '' }
        next(new restify.NotAuthorizedError());
    } else {
        next();
    }

    next();
}//function verifyAuthorizedUser(req, res, next)

然后,我打电话给server.use(verifyAuthorizedUser(req, res, next));。不幸的是,我遇到了这个错误ReferenceError: req is not defined

试试 server.use(verifyAuthorizedUser)。此回调函数将传递所有参数。

您应该传递函数本身,而不是对函数的调用:

server.use(verifyAuthorizedUser);

编辑:更多详情:

  • verifyAuthorizedUser(req, res, next) 是对函数 verifyAuthorizedUser 调用 。它的值将是该函数的 return 值。并且需要定义 reqresnext,但它们不是。

  • 你可以这样写:

    server.use(function(req,res,next)
    {
        verifyAuthorizedUser(req, res, next);
    });
    

但这只是无缘无故地添加额外的代码。

  • server.use(verifyAuthorizedUser()); 也是对该函数的 调用 ,并且您还有一个额外的问题,即您没有将任何参数传递给需要一些参数的函数,所以它显然会崩溃。

某些函数(例如 restify.queryParser)可能 return 一个函数,在这种情况下,您将调用第一个函数(使用 ())以获取用作回调。

您不需要解析回调中的参数。就这样

server.use(verifyAuthorizedUser)

有关详细信息,请查看 here