I'm kind of new to express and node.js, and I can't figure out the difference between app.use and app.get. It seems like you can use both of them to send information. For example:
app.use('/',function(req, res,next) {
res.send('Hello');
next();
});
seems to be the same as this:
app.get('/', function (req,res) {
res.send('Hello');
});
Best Answer
app.use()
is intended for binding middleware to your application. Thepath
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: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 theGET
HTTP verb:GET /
And, the equivalent routing for your example of
app.use()
would actually be:(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 andnext('route')
.Within each
app.get()
is a call toapp.use()
, so you can certainly do all of this withapp.use()
directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.Examples:
For simple, static routes:
vs.
With multiple handlers for the same route:
vs.
With parameters:
vs.