Beginner LevelExpress JS
What is the difference between app.use() and app.all() in Express routing?
❓ Interview Prompt: Compare app.use() middleware mounting vs app.all() exact route matching across HTTP verbs.
Both 'app.use()' and 'app.all()' execute logic across multiple HTTP methods (GET, POST, PUT, DELETE), but differ in path matching:
1. 'app.use([path], middleware)':
•
Designed for mounting middleware.
•
Prefix Matching: Matches any path starting with the specified prefix! 'app.use("/api", fn)' matches '/api', '/api/users', '/api/users/42/orders', etc.
2. 'app.all(path, handler)':
•
Designed for mounting route handlers.
•
Exact Path Matching: Matches ALL HTTP methods, but requires exact URL path matching (or strict route pattern matching). 'app.all("/api", fn)' matches '/api', but will NOT match '/api/users'!
Code Implementation Example
javascript
import express from 'express';
const app = express();
// 1. app.use matches URL prefixes (Matches /api, /api/users, /api/settings!)
app.use('/api', (req, res, next) => {
console.log('API Prefix Middleware triggered');
next();
});
// 2. app.all matches ALL HTTP verbs for EXACT path /api/health
app.all('/api/health', (req, res) => {
res.json({ status: 'OK', method: req.method });
});💡Comparing app.use prefix matching vs app.all exact path matching across HTTP verbs.
🎯 Interview Key Takeaway
app.use() matches URL prefixes for middleware; app.all() matches all HTTP verbs for an exact URL path route.
#app.use#app.all#Routing#Beginner
Back to all Express JS Questions→