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

  1. Express Routers are mini versions of Express applications.
  2. They allow you to modularize routes and middleware, making your application more organized and maintainable.

Setting Up Express and Creating a Basic Server

  1. First, create a new Node.js project and install the Express package
  2. npm init
    npm install express
    
  3. Create a basic Express server as described in the previous guide.

Introduction to Express Router

  1. A Router is an instance of the Express.js framework that provides route methods.
  2. 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

  1. 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

  1. 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

  1. 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

  1. 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);