0
0
Expressframework~5 mins

app.all and app.use for catch-all in Express

Choose your learning style9 modes available
Introduction

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.

When you want to handle every HTTP method (GET, POST, etc.) for a specific route.
When you want to create a fallback route for any unmatched URL.
When you want to add middleware that runs for all routes.
When you want to show a 404 page for unknown routes.
When you want to log or process every request regardless of method or path.
Syntax
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.

Examples
This handles GET, POST, PUT, DELETE, etc. on '/example'.
Express
app.all('/example', (req, res) => {
  res.send('All methods on /example');
});
This middleware runs for every request, no matter the path or method.
Express
app.use((req, res, next) => {
  console.log('Request received');
  next();
});
This middleware runs for any route starting with '/admin'.
Express
app.use('/admin', (req, res, next) => {
  console.log('Admin area accessed');
  next();
});
This catches all routes not matched earlier and sends a 404 response.
Express
app.all('*', (req, res) => {
  res.status(404).send('Page not found');
});
Sample Program

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.

Express
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}`);
});
OutputSuccess
Important Notes

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.

Summary

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.