Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express middleware: app.use and app.all

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?

like image 830
jamiltz Avatar asked Jun 15 '13 11:06

jamiltz


People also ask

What is the difference between app use and app all?

app. use only see whether url starts with specified path;app. all will match complete path.

What is app all in Express?

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.

What is the difference between app use and app get in express JS?

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.


1 Answers

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.

like image 150
ivoszz Avatar answered Sep 21 '22 03:09

ivoszz