If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
ExpressJS में routes / URLs को manage करने के लिए express.Router class का use किया जाता है। Router instance एक complete middleware है जिसकी help से हम easily routing maintain कर सकते हैं।
अगर आपको याद हो पिछले topic में हमने एक test 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}`);
});
C:\Users\HP\Desktop\expressjs\test>node app.js Server is running at http://localhost:8000
run करने के बाद अगर आप http://localhost:8000/test या http://localhost:8000 hit करेंगे तो आपको Output दिखा जाएगा।
अब suppose कीजिये आपके पास कई routes / URLs हैं तो आप सभी routes को तो अपनी main file में नहीं रख सकते हैं , क्योंकि फिर इन्हे manage करना easy हो जायगा। ऐसी situation में express.Router instance का use करते हैं। और सभी routes को separate file में रखते हैं।
अब ऊपर दिए गए routes को आप एक नयी file routes.js में रख दीजिये।
File : routes.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.');
});
module.exports = router
File : app.js
// import express module.
const express = require('express');
const app = express();
const port = 8000;
// now get 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 वे यही है कि आप Application में module के according routes को अलग ही manage करें।
I Hope, आपको ExpressJS में routing के बारे में अच्छे से समझ आया होगा।
Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.
Get connected with me. :) LinkedIn Twitter Instagram Facebook