简体   繁体   中英

How to configure dynamic routes with express.js

I have a route.js which looks like this:

module.exports = function(app) {

  app.get('/tip', function(req, res) {
    res.render("tip");
  });

  app.get('/article', function(req, res) {
   res.render("article");
  });

  app.get('/article1', function(req, res) {
   res.render("article1");
  });

  app.get('/article2', function(req, res) {
   res.render("article2");
  });

  app.get('/article3', function(req, res) {
   res.render("article3");
  });

  app.get('/modules/:name', function(req, res) {
    var name = req.params.name;
    res.render('modules/' + name);
  });

  app.get('/modules/esaver/:name', function(req, res) {
    var name = req.params.name;
    res.render('modules/esaver/' + name);
  });

};

I would do the same thing you did for /modules/:name

app.get('/article/:id', function(req , res){
  res.render('article' + req.params.id);
});

It would be more meaningful from a rest point of view.

If you cannot do it for any particular reason you might want to do something like:

var articlesEndpoints = ['/article2', '/article3'];
articlesEndpoints.forEach(function(name) {
  app.get(name, function(req, res) {
    res.render(name);
  });
});

Is this what you meant?

Finally got it working..

app.get('/:name(article|article2|article3)?', function(req, res) {
    var name = req.params.name;
    res.render(name);
});

There are many ways to implement dynamic express routes. It depends to a great extent on the structure you have implemented in your project, here I leave an example of dynamic routes and I hope it will be useful.

module.exports = (function(myCustomRoutes) {
   let express = require('express');
   let router  = express.Router();
   let methods = Object.keys(myCustomRoutes); // getting methods ('get', 'post'... etc)
   let routesMethod = null;
   let url = null;

   for(i in methods) {
      routesMethod = Object.keys(myCustomRoutes[methods[i]]);
      for(j in routesMethod) {
         url = '/' + routesMethod[j];
         url += '/:' + myCustomRoutes[methods[i]][routesMethod[j]].params.join('/:');console.log(url);
         router[methods[i]](url, myCustomRoutes[methods[i]][routesMethod[j]].controller);
      }
   }

   return router;
})();

Here is what I did to create dynamic APIs while I am in control over which API allows access to which methods. To maintain the APIs from now on, you can just edit the APIs array.

const APIs = [
    {
        route: 'order',
        methods: ['get', 'post']
    },
    {
        route: 'item',
        methods: ['get']
    },
]
APIs.forEach(api => {
    api.methods.forEach(method => {
        app[method]('/' + api.route, (req, res) => require('./routes/' + api.route)[method](req, res))
    })
})

Here are a couple of other solutions:

app.get(^\/article(\d{1,3})?\/?$, function(req, res, next) {
  var n;
  if (req.params[0])
    n = parseInt(req.params[0], 10);

  if (!n || (n > 0 && n < 900))
    res.render('article' + (n ? n : ''));
  else
    next();
});

or use app.all for the first solution or use a generic middleware:

app.use(function(req, res, next) {
  var m = ^\/article(\d{1,3})?\/?$.exec(req.url);
  if (m) {
    var n;
    if (m[0])
      n = parseInt(m[0], 10);

    if (!n || (n > 0 && n < 900))
      return res.render('article' + (n ? n : ''));
  }
  next(); 
});

I create a new module called: jadewalker<\/a> . It will create router code automatically.

//- jadewalker=/b,/b/:id
doctype html
html
 title b.jade
body
  p b.jade
  p params: #{params.id}

It's work on my project

routesPath = path.join(__dirname, 'routes');

fs.readdirSync(routesPath).forEach(function(file) {
  require(routesPath + '/' + file)(app);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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