Home > Blockchain >  creating dynamic routes using nodejs
creating dynamic routes using nodejs

Time:11-26

app.js

  // Calling Routes
  require("./routes")(app);

router folder index.js

module.exports = function (app) {
  app.use("/", require("./all_routes"));
}

all_routes.js

var express = require("express");
var router = express.Router();

router.get("/", function (req, res, next) {
 res.render("home/index.html");
});

//About Page
router.get("/about", function (req, res, next) {
 res.render("about/index.html");
});

//Contact 
router.get("/contact", function (req, res, next) {
 res.render("contact/index.html");
});

//product
router.get("/product", function (req, res, next) {
 res.render("product/index.html");
});

//product list
router.get("/product/demo-product", function (req, res, next) {
 res.render("demo-product/index.html");
});

router.get("/product/request-product", function (req, res, next) {
 res.render("request-product/index.html");
});

//service
router.get("/service", function (req, res, next) {
 res.render("product/index.html");
});

//service list
router.get("/service/what-we-do", function (req, res, next) {
 res.render("what-we-do/index.html");
});

router.get("/service/how-we-do", function (req, res, next) {
 res.render("how-we-do/index.html");
});

I am trying to reduce the code in all_routes.js file has same code is repeating again and again

I searched online and trying to create it dynamically but getting no success is there any way I can reduce the line of code as I have given the follow of my code above

CodePudding user response:

If you'd like to cut down on boilerplate of all your get routes, one option is to create an object to map your routes to the files they're loading. Then you can iterate over that object and add the routes to your router.

const routes = {
  "/": "home/index.html",
  "/about": "about/index.html",
  "/contact": "contact/index.html"
  // Add others here
}

for (let key in routes) {
  router.get(key, function (req, res, next) {
    res.render(routes[key]);
  });
}

Edit: If your routes are consistent in that the index.html file will always be in the directory named after the part after the last / in your route, you can potentially use an array and some fancy logic. Just don't break the rule!

const routes = [
  "/contact",
  "/product",
  "/product/demo-product", 
  "/product/request-product"
]

routes.forEach(route => {
  const path = /[^/]*$/.exec(route)[0];
  router.get(route, function (req, res, next) {
    res.render(`${path}/index.html`);
  });
})
  • Related