How to Separate Routers and Controllers in Node.js ?
Last Updated :
01 Aug, 2024
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.
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.
npm init -y
Step 2: Install the necessary packages/libraries in your project using the following commands.
npm install express
Step 3: Create Server File
Create an 'app.js' file, inside this file require an express Module, and create a constant 'app' for creating an instance of the express module.
const express = require('express')
const app = express()
Step 4: Creating Routers
Now let's set up three get routes for '/', '/about', and '/contact, inside this route, we will set up a callback function that sends the string, "Home", "About" and "Contact" respectively.
app.get('/', (req, res) => {
res.send("Home");
});
app.get('/about', (req, res) => {
res.send("About");
});
app.get('/contact', (req, res) => {
res.send("Contact");
});
Step 5: Set up a port to run our server
We will do it by using the express, listen to the method.
app.listen(3000, () => {
console.log("listening on http://localhost:3000");
})
Example: Implementation to separate routers and controllers in Node.js
Node
// index.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send("Home");
});
app.get('/about', (req, res) => {
res.send("About");
});
app.get('/contact', (req, res) => {
res.send("Contact");
});
app.listen(3000, () => {
console.log("listening on http://localhost:3000");
});
Step to run the application: Inside the terminal type the following command
node app.js
Output:
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");
});
Separate Controllers
Step 1: Create a folder for Controllers
Let's create a folder inside the project folder, let's call it controllers, inside this folder, create three files, homecontroller.js, aboutcontrollerr.js, and contactcontroller.js.
Step 2: Setup Controller files
Inside each file, we have to copy the respective controller from the app.js to the respective file and simply export it.
JavaScript
// homecontroller.js
module.exports = (req, res) => {
res.send("Home")
};
JavaScript
// aboutcontroller.js
module.exports = (req, res) => {
res.send("About")
};
JavaScript
// contactcontroller
module.exports = (req, res) => {
res.send("Contact")
};
Step 3: Import the controller in each router file respectively, then replace the callback function with it
const { Router } = require('express');
const home = require('../controllers/homecontroller')
const app = Router();
app.get('/', home);
module.exports = app;
Output:
Similar Reads
How to create nested controllers in Angular.js ?
A controller in AngularJS is a JavaScript object created with the help of a JavaScript object constructor. A controller can contain properties and functions. Controllers are used for controlling the application data of an AngularJS application. In this article, we will see the nested controllers in
4 min read
How to use Routes with serve-static Files in Node.js ?
Using serve-static files with routes in a Node.js application involves creating a server with Express, defining routes, and serving static files like HTML, CSS, JavaScript, images, etc. Hereâs an article explaining how to use serve-static with routes in Node.js.Serving Static Files with Routes in No
3 min read
How to handle Nested Routes in React Router ?
React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in
3 min read
How to Catch All Routes in Next.js ?
To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure.Catch all routesTo catch all routes in next js, We willCreate a file named [...gfg].js in
2 min read
How to Dynamically Call Router Function in Node.js ?
In Node.js Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function
4 min read
How to Setup Regex for ExpressJS Router URL in Node.js ?
ExpressJS Router is a class that acts as a middleware to provide route handling or determining how an application responds to a client requests, of various HTTP methods, to a particular URI.ApproachSetting up regex for Express.js router URLs in Node.js involves defining custom patterns using regular
3 min read
How to Create Multiple Routes in the Same Express.js Server ?
Creating multiple routes in an Express.js server involves defining routes in separate modules. This modular approach allows for better organization and maintainability by managing different routes independently and mounting them in the main server file. ApproachTo create multiple routes in an Expres
2 min read
How to Manage Sessions and Cookies in Express JS?
Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of
4 min read
How To Get Current Route In Next.js?
Next.js is a popular React framework that makes it easy to build server-side rendered and static web applications. One common task in web development is determining the current route or URL of the page. In Next.js, this can be done using the built-in useRouter hook. This article will guide you throu
3 min read
How To Create a Simple HTTP Server in Node?
NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
3 min read