ExpressJS में routes / URLs को manage करने के लिए express.Router class का use किया जाता है। Router instance एक complete middleware है जिसकी help से हम easily routing maintain कर सकते हैं।

ExpressJS Routing Example

अगर आपको याद हो पिछले topic में हमने एक express-app name का छोटा सा application बनाया था , उसी में continue करते हुए कुछ नए routes add करते हैं। Normally हम routes को express instance के through अपने application की main file app.js / server.js / index.js में रखते थे।

// import express module. const express = require('express'); const app = express(); const port = 8000; // define routes. app.get('/', function(req, res){ res.send('This is home page.'); }); app.get('/test', function(req, res){ res.send('Test route.'); }); //listen server. app.listen(port, function () { console.log(`Server is running at http://localhost:${port}`); });

run करने के बाद अगर आप http://localhost:8000/test या http://localhost:8000 hit करेंगे तो आपको Output दिखा जाएगा।

RxpressJS Router

अब suppose कीजिये आपके पास कई routes / URLs हैं तो आप सभी routes को तो अपनी main file में नहीं रख सकते हैं , क्योंकि फिर इन्हे manage करना easy हो जायगा। ऐसी situation में express.Router instance का use करते हैं। और सभी routes को separate file में रखते हैं।

अब ऊपर दिए गए routes को आप एक नयी file routes.js में रख दीजिये।

// File : router.js. // Import Router instance. const router = require("express").Router(); // now define routes using router. router.get('/', function(req, res){ res.send('This is home page.'); }); router.get('/test', function(req, res){ res.send('Test route.'); }); router.post('/post-test', function(req, res){ res.send('Post request route.'); }); // export router. module.exports = router;

अब इस routes.js को आप simply one line statement में अपनी main server file में add करके सभी routes को use में ले सकते हैं।

const express = require('express'); const app = express(); const port = 8000; // now add routes from routes.js. const myroutes = require("./routes") app.use('/', myroutes) // that's it :) // listen server. app.listen(port, function () { console.log(`Server is running at http://localhost:${port}`); });

तो जैसा कि example में आप देख सकते हैं कि Router instance की help से हम easily कितने ही routes को easily maintain करते हैं। और actually में standard way यही है कि आप Application में module के according routes को अलग ही manage करें।

I Hope, आपको ExpressJS में routing के बारे में अच्छे से समझ आया होगा।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers