Use of routers in Express JavaScript

Routers are used in express to write clean code. Using routers we can create different JavaScript files and call using the main file. Here in this tutorial, I have created two different file manager and admin call using the app.js file. It will work on the port number 3000 (use according to your convenient).

Use of Routers in Express.js

File app.js

Here this file is the main file where all other files are called when the server will execute. Using method app.use() we will check which will be executed.
When we check only “/” then it will be executed always in case of app.use() method only.

const express =require('require');
const app =express();
const adminRoute=require("admin.js");
const managerRoute=require("manager.js");
      console.log("root file");

File admin.js

In this file new page is created that is “/login”. When URL matches then it will print “Admin Login page” and in console, it will print “Admin page”.

const express =require('require');
const router =express.Router();
           console.log("Admin page"); 
           req.send("Admin Login Page");     

File manager.js

In this file report page created. When URL matches then it will print “Manager Page” and in console, it will print “Manager Page”.

const express =require('require');
const router =express.Router();
             console.log("Manager Page");    
             req.send("Manager Page");

module.exports method is used to export file so that the main file can read it.
Output to the website when the URL matches the login page:

Admin Login Page

Output to the website when the URL matches the manager page:

Manager Page

Check out another blog as well:

Leave a Reply

Your email address will not be published. Required fields are marked *