Sometimes, we want to add REST endpoints with Express.js nested router.
In this article, we’ll look at how to add REST endpoints with Express.js nested router.
How to add REST endpoints with Express.js nested router?
To add REST endpoints with Express.js nested router, we should make sure our route URL and request methods follow the REST convention.
For instance we write
const express = require('express');
const app = express();
const userRouter = express.Router();
const itemRouter = express.Router({
mergeParams: true
});
userRouter.use('/:userId/items', itemRouter);
userRouter.route('/')
.get((req, res) => {
res.status(200)
.send('hello users');
});
userRouter.route('/:userId')
.get((req, res) => {
res.status(200)
.send(req.params.userId);
});
itemRouter.route('/')
.get((req, res) => {
res.status(200)
.send(`items ${req.params.userId}`);
});
itemRouter.route('/:itemId')
.get((req, res) => {
res.status(200)
.send(`item ${req.params.itemId} user ${req.params.userId}`);
});
app.use('/user', userRouter);
app.listen(3000);
to nest itemRouter
in userRoute
.
We have
userRouter.use('/:userId/items', itemRouter);
to nest itemRouter
in userRouter
.
We set mergeParams
to true
so that the URL from userRouter
is combined with the URLs of the routes with itemRouter
.
As a result, we get the following results when the following requests are made:
- GET /user -> hello user
- GET /user/5 -> 5
- GET /user/5/items -> items 5
- GET /user/5/items/6 -> item 6 user 5
Conclusion
To add REST endpoints with Express.js nested router, we should make sure our route URL and request methods follow the REST convention.