We use app.all and app.use to handle all types of requests or routes that don't match any specific path. This helps catch everything else and respond properly.
app.all and app.use for catch-all in Express
app.all(path, callback) app.use([path], callback)
app.all listens to all HTTP methods for the given path.
app.use adds middleware that runs for all HTTP methods and paths starting with the given path. If no path is given, it runs for all routes.
app.all('/example', (req, res) => { res.send('All methods on /example'); });
app.use((req, res, next) => {
console.log('Request received');
next();
});app.use('/admin', (req, res, next) => { console.log('Admin area accessed'); next(); });
app.all('*', (req, res) => { res.status(404).send('Page not found'); });
This Express app shows how app.use logs every request, app.all handles all methods on '/all', and a catch-all app.all('*') sends a 404 for unknown routes.
import express from 'express'; const app = express(); const port = 3000; // Middleware for all requests app.use((req, res, next) => { console.log(`Received ${req.method} request for ${req.url}`); next(); }); // Handle GET on /hello app.get('/hello', (req, res) => { res.send('Hello World'); }); // Catch all HTTP methods on /all app.all('/all', (req, res) => { res.send(`You made a ${req.method} request to /all`); }); // Catch all unmatched routes app.all('*', (req, res) => { res.status(404).send('Sorry, page not found'); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Order matters: Place app.use and app.all catch-alls after specific routes so they don't block them.
app.use can take a path prefix and runs for all methods and sub-paths.
Use app.all('*') to catch any route not matched earlier, often for 404 pages.
app.all handles all HTTP methods for a specific path.
app.use adds middleware for all methods and paths starting with a prefix.
Use catch-all routes to handle unknown URLs or add global middleware.