What's the difference between express's router.use and router.all?

has tested blocking routes, and setting cross-domain has the same effect:
index.js:

router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type");
   const url=req.url
    if (url.indexOf("test")!=-1){
       return res.json("test")
    }
    next();
});
...
router.all("*",function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    const url=req.url
    if (url.indexOf("test")!=-1){
       return res.json("test")
    }
    next();
});
...

what"s the difference between local testing and which one should be used?

Aug.02,2021

there are two ways to add middleware to express

  1. app.use add ordinary middleware
  2. app [method] add routing middleware

when you use router.use, it is equivalent to adding ordinary middleware, you will add a Layer object (the object that holds the information of the middleware function) in the Router stack;
when you use router.all (*), it is equivalent to adding routing middleware, the Layer object added in the Router stack holds the routing or pointer of the routing middleware, and the real routing middleware will be added to the Route stack.


Cross-domain and route interception have something in common, that is, for all kinds of requests, router.all (), is generally used and router.use () is mainly used for middleware processing under the specified path. Of course, it can also be used to match any path, but it is used to indicate that for all requests, it must be used before other routes.

Menu