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

时间:2023-01-27 11:26:07

I was given a task to recreate Express' middleware architecture and I think I'm getting lost in callback land at the moment. I'm able to respond to the requests and everything, but what I'm having trouble with is implementing the next() functionality the Express provides. Here is the relevant code I've got so far:

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

using my middleware:

使用我的中间件:

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");
});

then in the actual middleware file I have:

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

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);
    }
}

basically what I thinkk I need is access to cb's arguments, which are the request and the response to filter out the request url and write the appropriate message, but I can't access them. Logging cb.length works, but thats just getting the length of the arguments passed to it, I can't access the actual values of the arguments. Also, Node's server.on event only has two arguments, request and response, so I'm a bit confused as to how Connect / Express introduce the 3rd argument next. Am I doing this the right way? or way off track?

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

1 个解决方案

#1


One way you can append arguments to a function is to invoke it explicitly inside an anonymous function.

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

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

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

You can also look at bind, call, and apply for some other possible options.

您还可以查看绑定,调用和应用其他一些可能的选项。

#1


One way you can append arguments to a function is to invoke it explicitly inside an anonymous function.

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

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

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

You can also look at bind, call, and apply for some other possible options.

您还可以查看绑定,调用和应用其他一些可能的选项。