繁体   English   中英

使用 nodejs 创建动态路由

[英]creating dynamic routes using nodejs

应用程序.js

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

路由器文件夹 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");
});

我正在尝试减少all_routes.js文件中的代码相同的代码一次又一次地重复

我在网上搜索并尝试动态创建它但没有成功有什么办法可以减少代码行,因为我在上面给出了我的代码

如果您想减少所有get路线的样板,一种选择是创建一个 object 到 map 您的路线到他们正在加载的文件。 然后您可以遍历该 object 并将路由添加到您的路由器。

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]);
  });
}

编辑:如果您的路线一致,因为index.html文件将始终位于以您路线中最后一个/之后的部分命名的目录中,您可以使用数组和一些奇特的逻辑。 只是不要打破规则!

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`);
  });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM