Is there a difference between
app.use('/some/path', function(req, res, next() {})
and
app.all('/some/path', function(req, res, next() {})
They are both middleware functions that get called for /some/path requests only, right?
app. use only see whether url starts with specified path;app. all will match complete path.
The app. all() method can be used for all types of routings of a HTTP request, i.e., for POST, GET, PUT, DELETE, etc., requests that are made to any specific route. It can map app types of requests with the only condition that the route should match.
app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.
There is big difference between the use of these two examples. Functions registered with app.use
are general middleware functions and is called appropriate to their position on the middleware stack, typically inside an app.configure
function. This type of middleware is usually placed before app.route
, with the exception of error handling functions.
On the other hand app.all
is a routing function (not usually called middleware) which covers all HTTP methods and is called only inside app.route
. If any of your previous router function matches the /some/path
and did not call the next
callback, app.all
will not be executed, so app.all
functions are usually on the beginning of your routing block.
There is also third type of middleware, used in your routing functions, eg.
app.get('/some/path', middleware1, middleware2, function(req, res, next) {});
which is typicaly used for limiting access or perform general tasks related to /some/path
route.
For practical application you can use both functions, but be careful of the difference in behaviour when using app.use
with /some/path
. Unlike app.get
, app.use
strips /some/path
from the route before invoking the anonymous function.
You can find more in the documentation of express.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With