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.
Express' app. get() function lets you define a route handler for GET requests to a given URL. For example, the below code registers a route handler that Express will call when it receives an HTTP GET request to /test .
As per the documentation GET requests are meant to fetch data from specified resources and POST requests are meant to submit data to a specified resource.
use(); mounts middleware for the routes served by the specific router, app. use(); mounts middleware for all routes of the app (or those matching the routes specified if you use app.
app.use()
is intended for binding middleware to your application. The path
is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:
// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();
app.use('/subapp', require('./subapp'));
// ...
By specifying /
as a "mount" path, app.use()
will respond to any path that starts with /
, which are all of them and regardless of HTTP verb used:
GET /
PUT /foo
POST /foo/bar
app.get()
, on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET
HTTP verb:
GET /
And, the equivalent routing for your example of app.use()
would actually be:
app.all(/^\/.*/, function (req, res) {
res.send('Hello');
});
(Update: Attempting to better demonstrate the differences.)
The routing methods, including app.get()
, are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route')
.
Within each app.get()
is a call to app.use()
, so you can certainly do all of this with app.use()
directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.
Examples:
For simple, static routes:
app.get('/', function (req, res) {
// ...
});
vs.
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
// ...
});
With multiple handlers for the same route:
app.get('/', authorize('ADMIN'), function (req, res) {
// ...
});
vs.
const authorizeAdmin = authorize('ADMIN');
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
authorizeAdmin(req, res, function (err) {
if (err) return next(err);
// ...
});
});
With parameters:
app.get('/item/:id', function (req, res) {
let id = req.params.id;
// ...
});
vs.
const pathToRegExp = require('path-to-regexp');
function prepareParams(matches, pathKeys, previousParams) {
var params = previousParams || {};
// TODO: support repeating keys...
matches.slice(1).forEach(function (segment, index) {
let { name } = pathKeys[index];
params[name] = segment;
});
return params;
}
const itemIdKeys = [];
const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
app.use('/', function (req, res, next) {
if (req.method !== 'GET') return next();
var urlMatch = itemIdPattern.exec(req.url);
if (!urlMatch) return next();
if (itemIdKeys && itemIdKeys.length)
req.params = prepareParams(urlMatch, itemIdKeys, req.params);
let id = req.params.id;
// ...
});
Note: Express' implementation of these features are contained in its
Router
,Layer
, andRoute
.
app.use
is the "lower level" method from Connect, the middleware framework that Express depends on.
Here's my guideline:
app.get
if you want to expose a GET method.app.use
if you want to add some middleware (a handler for the HTTP request before it arrives to the routes you've set up in Express), or if you'd like to make your routes modular (for example, expose a set of routes from an npm module that other web applications could use).Simply
app.use means “Run this on ALL requests”
app.get means “Run this on a GET request, for the given URL”
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.
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.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