Lev Lev - 1 month ago 5
Node.js Question

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 ?

Answer

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.

Comments