Reputation: 13069
According to the docs for express
, the path
parameter is optional for app.use
, so to apply the middleware to any incoming request you can write:
app.use(function (req, res, next) {
res.send('ANY request');
next();
});
But for app.get
the path
parameter is apparently not optional, so to apply the middleware to any incoming GET
request you have to write:
app.get('/', function (req, res, next) {
res.send('GET request');
next();
});
But I find that it doesn't complain if I do miss out the path:
app.get(function (req, res, next) {
res.send('GET request');
next();
});
So, are the above two definitions equivalent, or is the second one doing something different to the first one?
I'm also not sure of the difference between specifying /
or *
as the path
:
app.get('*', function (req, res, next) {
res.send('GET request');
next();
});
So, in summary, is there any difference between app.get('/', fn)
and app.get('*', fn)
and app.get(fn)
?
Upvotes: 0
Views: 73
Reputation: 29132
Somewhat confusingly, there are two methods called app.get
:
https://expressjs.com/en/4x/api.html#app.get
One is the converse to app.set
, the other is the one for handling GET requests. In practice JS only allows a single method, so internally Express checks how many arguments are passed to work out which one you meant:
So while using app.get(fn)
might not complain, it won't actually work as a route because it'll be treating it as the other form of get
.
The difference between app.get('*', ...)
and app.get('/', ...)
is that the *
will match any path whereas /
will only match the exact path /
(and nothing more). This is different from app.use
, where the path is treated like a 'starts with'.
You may find the answer I gave here helpful to understand how paths differ between get
and use
: Difference between app.use and app.get *in proxying*.
Upvotes: 1