如何将参数传递给express.js中的嵌套控制器?

时间:2017-12-03 00:06:51

标签: node.js express

我有这样的路由器:

app.get('/rest/userList', (req, res) => {

    UserList.find({}, (err, users) => {
        if (err) res.send(err);
        res.json(users);
    });
});

我想改变它:

app.get('/rest/userList', getUsers);

function getUsers(req, res) { 
    UserList.find({}, createResponse);
}

function createResponse(err, users) {
    if (err) return res.send(err);
    return res.send(users);
}

然而;在createResponse函数' res'未定义。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您可以使用.bind()将额外参数绑定到回调:

app.get('/rest/userList', getUsers);

function getUsers(req, res) { 
    UserList.find({}, createResponse.bind(null, res));
}

function createResponse(res, err, users) {
    if (err) return res.send(err);
    return res.send(users);
}

答案 1 :(得分:1)

app.get('/rest/userList', getUsers, createResponse);

function getUsers(req, res, next) { 
    UserList.find({}, function (err, users) {
        if (err) {
            req.errr = err;
        } else {
            req.users = users;
        }

        next();
    });
}

function createResponse(req, res) {
    if (req.err) return res.send(req.err);
    return res.send(req.users);
}