Difference between app.use
& app.get
:
app.use
? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.
app.get
? It is only for handling GET HTTP requests.
Now, there is a confusion between app.use
& app.all
. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests.
But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.
app.use()
? It takes only one callback.
app.all()
? It can take multiple callbacks.
app.use()
will only see whether url starts with specified path.
But, app.all()
will match the complete path.
For example,
app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
app.all( "/book" , handler);
// will match /book
// won't match /book/author
// won't match /book/subject
app.all( "/book/*" , handler);
// won't match /book
// will match /book/author
// will match /book/subject
next()
call inside the app.use()
will call either the next middleware or any route handler, but next()
call inside app.all()
will invoke the next route handler (app.all()
, app.get/post/put...
etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.