In addition to what Jonathan Lonowski said in the posted link, it might help to not compare use
to get
and post
, but to compare it to all
because both all
and use
work regardless of the HTTP verb used while that's obviously not true for get
. Everything I'm about to say applies if you replace "all" with "get", it'll just narrow that handler down to a specific HTTP verb.
So, what's the difference between all
and use
?
app.all will handle incoming requests at the specified URL path regardless of the HTTP verb, just as app.use
does. However, how it compares the requested URL to the handler is different. For example:
var r = express.Router();
r.use('/foo', function (...) { ... }); // Route A
r.all('/bar', function (...) { ... }); // Route B
If you make a request to /foo/123
Route A will be run.
If you make a request, however, to /bar/123
Route B will NOT be run.
This is because with HTTP verbs express compares the full path, but with 'use' it only cares about the beginning of the url. Because the URL /foo/123
begins with /foo
Route A will run, but because /bar/123
does not match the FULL URL, Route B will not be. Note: You could make .all
behave in the same way: r.all('/bar/*', ...)
, but use
is easier and more appropriate for this.
So, what you would tend to mount with one vs the other is different. For example:
var app = express();
var router1 = express.Router();
var router2 = express.Router();
router2.all('*', function (req, res) { ... }); // Must specify a path!
router1.use('/secondary-routes', router2); // Can't do this with all.
app.use(router1); // Look Ma, no path!
Here I've used all
to handle a request coming in, where I've used use
to mount an entire router. Also, note that the usage of router.METHOD
functions require a URL string as the first parameter, while use
does not.
At the end of the day, if you:
- Want all requests that come in under a given path (or even every request) to use the specified middleware, or
- Want to mount an entire sub router/application, or
- Want to include a plugin into your application
... Then use
is probably what you want.
If you:
- Are handling a specific request at a specific URL path (i.e. probably not doing a * match in the URL)
- Generally won't be calling
next
and will instead actually be handling the request
... Then an HTTP verb method (like get
, post
or all
) is probably what you want.