app.all for a catch-all route?Consider this Express code snippet:
const express = require('express');
const app = express();
app.all('*', (req, res) => {
res.send('Catch-all with app.all');
});
app.listen(3000);What will a GET request to /anything respond with?
const express = require('express'); const app = express(); app.all('*', (req, res) => { res.send('Catch-all with app.all'); }); app.listen(3000);
Think about what app.all does with the path '*'.
app.all('*', ...) matches all HTTP methods and all paths. So any request to any path will trigger this handler.
app.use behave as a catch-all middleware?Given this Express setup:
const express = require('express');
const app = express();
app.use((req, res) => {
res.send('Catch-all with app.use');
});
app.listen(3000);What happens when a GET request is made to /random?
const express = require('express'); const app = express(); app.use((req, res) => { res.send('Catch-all with app.use'); }); app.listen(3000);
Remember that app.use without a path matches all requests.
app.use without a path argument acts as a catch-all middleware for all HTTP methods and paths.
Which of these Express route definitions will cause a syntax error?
Check if all required arguments are present for app.all.
app.all requires a path as the first argument. Omitting it causes a syntax error.
app.use and app.all catch-all handlers exist?Consider this Express code:
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.write('Use start - ');
next();
});
app.all('*', (req, res) => {
res.end('All end');
});
app.listen(3000);What will a GET request to /test respond with?
const express = require('express'); const app = express(); app.use((req, res, next) => { res.write('Use start - '); next(); }); app.all('*', (req, res) => { res.end('All end'); }); app.listen(3000);
Think about how middleware passes control with next().
The app.use middleware writes 'Use start - ' and calls next(), passing control to app.all which ends the response with 'All end'.
Look at this Express code:
const express = require('express');
const app = express();
app.use((req, res, next) => {
next();
res.send('Catch-all response');
});
app.listen(3000);Why does a request to any path never get the 'Catch-all response'?
const express = require('express'); const app = express(); app.use((req, res, next) => { next(); res.send('Catch-all response'); }); app.listen(3000);
Think about the order of next() and res.send() calls.
Calling next() passes control to the next middleware or route. The res.send() after next() runs too late and is ignored because the response is already handled or the request moved on.