Express Routers Tutorial
Express Routers are a fundamental concept in Express.js that allows you to modularize and organize your routes and middleware.
Introduction to Express Routers
- Express Routers are mini versions of Express applications.
- They allow you to modularize routes and middleware, making your application more organized and maintainable.
Setting Up Express and Creating a Basic Server
- First, create a new Node.js project and install the Express package
- Create a basic Express server as described in the previous guide.
npm init
npm install express
Introduction to Express Router
- A Router is an instance of the Express.js framework that provides route methods.
- You can think of it as a smaller, separate version of your application that can be used to handle routes.
Creating and Using Router Instances
- Create a Router instance using express.Router() and use it like an Express app.
const express = require('express');
const app = express();
const router = express.Router();
Routing with Routers
- Define routes and associated middleware for a Router instance.
router.get('/', (req, res) => {
res.send('Router Home Page');
});
router.get('/about', (req, res) => {
res.send('About Us');
});
app.use('/router', router);
Organizing Routes with Routers
- Routers are particularly useful for organizing routes into separate files.
// users.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('User List');
});
module.exports = router;
// app.js
const express = require('express');
const app = express();
const usersRouter = require('./users');
app.use('/users', usersRouter);
Error Handling in Routers
- Routers can also handle errors just like Express applications.
router.get('/error', (req, res, next) => {
const error = new Error('This is a router error');
next(error);
});
router.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send('Router Error');
});
app.use('/router', router);