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");
app.use('/',(req,res,next)=>{
      console.log("root file");
      };
app.use(adminRoute);
app.use(managerRoute);
app.listen(3000);

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();
router.get('/login',(req,res,next)=>{      
           console.log("Admin page"); 
           req.send("Admin Login Page");     
       };
module.exports=router;

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();
router.get('/manager',(req,res,next)=>{      
             console.log("Manager Page");    
             req.send("Manager Page");
      };
module.exports=router;

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:

Output:
Admin Login Page

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

Output:
Manager Page

Check out another blog as well:

Leave a Reply

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