使用快速中间件的不同方式

时间:2022-07-31 23:56:12

I can set express middleware like this:

我可以像这样设置快速中间件:

app.use(function(req,res,next) {
    console.log("my middleware");
    return next();
});

And also like this:

还有这样:

app.get("/", function(req,res,next) {
     console.log("my other middleware");
},
function(req,res) {
     res.send("Test");
});

Aside from the fact that the first case is applied globally to all routes, and in the second case it is only applied to the specific route "/", do these behave identically?

除了第一种情况全局应用于所有路由这一事实,而在第二种情况下它仅应用于特定路由“/”,这些行为是否相同?

1 个解决方案

#1


3  

You have two differences. The first is correct... the first middleware is used for all requests and the second one is for anything matching your route of /.

你有两个不同之处。第一个是正确的......第一个中间件用于所有请求,第二个中间件用于匹配/的路由。

The second difference is that the first middleware is used for all verbs, whereas the second middleware is only use for GET requests.

第二个区别是第一个中间件用于所有动词,而第二个中间件仅用于GET请求。

#1


3  

You have two differences. The first is correct... the first middleware is used for all requests and the second one is for anything matching your route of /.

你有两个不同之处。第一个是正确的......第一个中间件用于所有请求,第二个中间件用于匹配/的路由。

The second difference is that the first middleware is used for all verbs, whereas the second middleware is only use for GET requests.

第二个区别是第一个中间件用于所有动词,而第二个中间件仅用于GET请求。