The following express routing matches GET /
but not GET /anything/else
.
app.get('/', (req, res, next) => {
res.send('I only answer to /');
});
Is Express Routing not prefix-based or "deep"?
I know this works but it seems wrong:
app.get('*', (req, res, next) => {
res.send('I answer to any path');
});
CodePudding user response:
app.get
must match the full path and stores it in req.path
, whereas app.use
matches a prefix and sets req.path
to the path after the prefix. You could write
app.use('/', (req, res, next) => {
if (req.method === "GET")
res.send('I answer to all GET requests');
else
next();
});
GET /anything/else
would be matched by app.use('/anything', ...)
, but then req.path = '/else'
.
CodePudding user response:
One possible fix although it's not as elegant would be:
app.get('/:paramname', () => {
res.send('I answer to any path')
});
If im not mistaken you could chain the parameters so it will answer to /hello/world
too. But you would have to try that...
Have a nice day