/api/data?const express = require('express'); const app = express(); function logMiddleware(req, res, next) { console.log('Middleware triggered'); next(); } app.use((req, res, next) => { if (req.path.startsWith('/api')) { logMiddleware(req, res, next); } else { next(); } }); app.get('/api/data', (req, res) => { res.send('Data response'); }); app.listen(3000);
The middleware checks if the request path starts with '/api'. For '/api/data', it does, so logMiddleware runs, logging the message. Then it calls next() to continue to the route handler, which sends the response.
Option A uses app.post which applies middleware only for POST requests to '/submit'. Option A uses app.use but does not handle the response properly. Option A has an assignment (=) instead of comparison (===), causing a bug.
const express = require('express'); const app = express(); app.use('/dashboard', (req, res, next) => { console.log('Middleware active'); next(); }); app.get('/dashboard', (req, res) => { res.send('Dashboard page'); }); app.listen(3000);
Express matches paths as prefixes for app.use with a path. If the request URL is '/dashboard/' (with trailing slash), it still matches '/dashboard' prefix, so the middleware runs. The problem is likely elsewhere.
req.user in the route handler after this middleware runs for a request to '/profile' with header Authorization: Bearer token123?const express = require('express'); const app = express(); app.use((req, res, next) => { if (req.headers.authorization?.startsWith('Bearer ')) { req.user = { id: 1, name: 'Alice' }; } next(); }); app.get('/profile', (req, res) => { res.json(req.user || null); }); app.listen(3000);
The middleware checks if the Authorization header starts with 'Bearer '. Since the request has 'Bearer token123', it sets req.user to the user object. The route handler then returns this object as JSON.
Middleware must be registered before the routes it affects to run first. Using app.use('/admin', loggerMiddleware) before defining '/admin' routes ensures it runs only for those routes and before their handlers.