Separate Routers

Step 1: Create a folder for Routers

Let’s create a folder inside the project folder, let’s call it routers, inside this folder, create three files, homerouter.js, aboutrouter.js, and contactrouter.js. 

Step 2: Setup Routers files

Inside each file, we have to import the Routers from the express. Then create an instance of that router, we will again call it an app, then copy the respected routers from the app.js to the respective file and simply export it.

JavaScript
// homerouter.js

const { Router } = require('express');
const app = Router();

app.get('/', (req, res) => {
    res.send("Home");
});

module.exports = app;
JavaScript
// aboutrouter.js

const { Router } = require('express');
const app = Router();

app.get('/about', (req, res) => {
    res.send("About");
});

module.exports = app;
JavaScript
// contactrouter.js

const { Router } = require('express');
const app = Router();

app.get('/contact', (req, res) => {
    res.send("Contact");
});

module.exports = app;
Node
// app.js

const express = require('express');
const home = require('./routers/homerouter');
const about = require('./routers/aboutrouter');
const contact = require('./routers/contactrouter');

const app = express();

app.use(home);
app.use(about);
app.use(contact);

app.listen(3000, () => {
    console.log("listening on http://localhost:3000");
});

How to Separate Routers and Controllers in Node.js ?

In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the application easier to understand and manage.

Table of Content

  • What Are Routers and Controllers?
  • Separate Routers
  • Separate Controllers

Similar Reads

What Are Routers and Controllers?

Routers: Handle the routing of HTTP requests to the appropriate controller functions. They define the endpoints and HTTP methods (GET, POST, PUT, DELETE) for your application.Controllers: Contain the business logic for handling requests and generating responses. They perform tasks like querying the database, processing data, and returning responses to the client....

Approach

We will create a simple Node.js application, using Express. This application returns the “Home” string for the main route, “About” for the About the route, and “Contact” for the contact route. Then we will separate the routers and controller into different javascript files....

Steps to Create NodeJS Application

Step 1: Initialize Node.js application by using the following command....

Separate Routers

Step 1: Create a folder for Routers...

Separate Controllers

Step 1: Create a folder for Controllers...