我将如何模仿express / connections next()功能?

时间:2015-05-13 15:17:31

标签: node.js express connect

我被赋予了重建Express'中间件架构的任务,我想我现在正迷失在回调的土地上。我能够响应请求和所有内容,但我遇到的问题是实现Express提供的next()功能。这是我到目前为止的相关代码:

使用我的中间件:

app.use(function(req, res, next){
    res.write("Humpty "); 
});
app.use(function(req, res, next){
    res.write("Dumpty "); 
});
app.use("/sat", function(req, res, next){
    res.end("sat on a wall \n");
});

然后在我的实际中间件文件中:

module.exports = {
    use: function(url, cb){    // how do i add a next() arg to cb?
        if(cb === undefined){    // if 1 arg passed, must be function
            cb = url;   
        }
        server.on("request", cb);
    }
}

基本上我认为我需要的是访问 cb 的参数,这是请求和过滤掉请求url并写入相应消息的响应,但我无法访问它们。记录cb.length是有效的,但那只是获取传递给它的参数的长度,我无法访问参数的实际值。此外,Node的 server.on 事件只有两个参数,请求响应,所以我对Connect / Express的方式有点困惑介绍第三个参数下一个。我这样做是对的吗?还是偏离轨道?

1 个答案:

答案 0 :(得分:1)

您可以向函数追加参数的一种方法是在匿名函数中显式调用它。

// cb and next must be defined in this scope.
// then...

server.on("request", function (req, res) {
    cb(req, res, next);
});

您还可以查看bindcallapply以了解其他一些可能的选项。