How to configure dynamic routes with express.js

前端 未结 7 2376
Happy的楠姐
Happy的楠姐 2020-12-07 20:32

I have a route.js which looks like this:

module.exports = function(app) {

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

  app.get         


        
相关标签:
7条回答
  • 2020-12-07 20:36

    It's work on my project

    routesPath = path.join(__dirname, 'routes');
    
    fs.readdirSync(routesPath).forEach(function(file) {
      require(routesPath + '/' + file)(app);
    });
    
    0 讨论(0)
  • 2020-12-07 20:37

    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?

    0 讨论(0)
  • 2020-12-07 20:40

    Finally got it working..

    In cases where I got, article1, article2 etc:

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

    In cases where I got multi level url, I created a custom function:

    function geturl(url) {
    
      app.get('/' + url + '/' + ':name', function(req, res){
        var name = req.params.name;
        res.render(url + '/' + name);
      });
    
    };
    
    0 讨论(0)
  • 2020-12-07 20:47

    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.

    RouterService.js

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

    CustomRoutes.js

    module.exports = (function() {
        let routes = {get: {}, post: {}};
        let routerService = require('./RouterService');
    
        // GET:  /dynamic1
        routes.get.dynamic1 = {
           params: [],
           controller: function(req, res, next) {
               res.send('route 1');
           }
        };
    
        // GET:  /dynamic2/:param1
        routes.get.dynamic2 = {
           params: [':param1'],
           controller: function(req, res, next) {
               res.send('route 2');
           }
        };
        // POST: /dynamic3/:param1/:param1
        routes.post.dynamic3 = {
           params: ['param1', 'param2'],
           controller: function(req, res, next) {
              res.send('route 3');
           }
        };
    
        /*
        *  Export a router with paths
        *  GET:  /dynamic1
        *  GET:  /dynamic2/:param1
        *  POST: /dynamic3/:param1/:param1
        **/
        return routerService(routes);
    })();
    

    app.js

    let express = require('express');
    let app = express();
    
    
    /*
     *  Option 1
     *  GET:  /dynamic1
     *  GET:  /dynamic2/:param1
     *  POST: /dynamic3/:param1/:param1
     **/
     app.use(require('CustomRoutes')());
    
    
    /*
     *  Option 2
     *  GET:  /api/v1/dynamic1
     *  GET:  /api/v1/dynamic2/:param1
     *  POST: /api/v1/dynamic3/:param1/:param1
     **/
     app.use('/api/v1', require('CustomRoutes')());
    
    0 讨论(0)
  • 2020-12-07 20:49

    I create a new module called: jadewalker. It will create router code automatically.

    We can simply add a jadewalker comment to your jade Or pug file.

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

    And add this module to our app. That's all.

    var app = require('koa')()
    var router = require('koa-router')();
    router = require('jadewalker')(router, path.join(__dirname, 'views'));
    app.use(router.routes());
    

    We can visit our jade file by the URL http://localhost:3000/b/abc. (^∀^)

    0 讨论(0)
  • 2020-12-07 20:50

    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))
        })
    })
    
    0 讨论(0)
提交回复
热议问题