简体   繁体   中英

path treated differently between app.use() and app.get()

How come when I do a GET request on /foo , my request passes through the first middleware function in example A, but bypasses it in example B ?

Example A

GET '/foo"

app.use('/', function(req, res, next) {
     console.log("req passes through here");
     next();
}

app.get('/foo', function(req, res, next) {
     console.log("then req passes through here");
}

Example B

GET '/foo"

app.get('/', function(req, res, next) {
     console.log("this part is bypassed...");
     next();
}

app.get('/foo', function(req, res, next) {
     console.log("then req passes through here");
}

app.use() and app.get() use the same path argument.

So how come the middleware mounted on / in not executed in example B ?

app.use() instructs the app to use the specified path for all methods (GET, PUT, POST, etc) on all calls. Specifically app.use :

Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

While app.get() instructs it to use the path for that specific method (GET) for that specific path only.

Routes HTTP GET requests to the specified path with the specified callback functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM