/api/users?const express = require('express'); const app = express(); const router = express.Router(); router.get('/users', (req, res) => { res.send('User list'); }); app.use('/api', router); app.listen(3000);
The router is mounted with app.use('/api', router), so all routes inside the router are prefixed with '/api'. The route /users inside the router becomes /api/users. So requesting /api/users matches and returns 'User list'.
In Express, to prefix routes in a router, you mount the router on the app with the prefix path: app.use('/admin', router);. Other options are invalid syntax or methods that don't exist.
const express = require('express');
const app = express();
const router = express.Router();
router.get('products', (req, res) => {
res.send('Product list');
});
app.use('/api', router);
app.listen(3000);Express route paths must start with a slash. The route is defined as 'products' instead of '/products', so it does not match '/api/products'. Adding the leading slash fixes the issue.
const express = require('express');
const app = express();
const router1 = express.Router();
const router2 = express.Router();
router2.get('/info', (req, res) => {
res.send('Info page');
});
router1.use('/details', router2);
app.use('/api', router1);
app.listen(3000);
What response will a GET request to /api/details/info return?The router2 is mounted on router1 at '/details', and router1 is mounted on app at '/api'. So the full path to router2's '/info' route is '/api/details/info'. The request matches and returns 'Info page'.
const router = express.Router();
router.get('/status', (req, res) => res.send('OK'));
app.use('/service1', router);
app.use('/service2', router);
What happens when a client requests /service2/status?Express allows mounting the same router multiple times with different prefixes. The router handles requests under both prefixes independently. So /service2/status returns 'OK'.