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.
// homerouter.js
const { Router } = require('express');
const app = Router();
app.get('/', (req, res) => {
res.send("Home");
});
module.exports = app;
// aboutrouter.js
const { Router } = require('express');
const app = Router();
app.get('/about', (req, res) => {
res.send("About");
});
module.exports = app;
// contactrouter.js
const { Router } = require('express');
const app = Router();
app.get('/contact', (req, res) => {
res.send("Contact");
});
module.exports = app;
// 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