如何使用express.js配置动态路由

时间:2014-09-02 12:06:47

标签: javascript node.js express

我有一个看起来像这样的route.js:

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

};

考虑到我有超过200条不同的路线需要创建,我最终会得到类似于' article1',' article2'等

我的app.js就像:

var express = require('express')
  ,http = require('http')
  ,fs = require('fs')
  ,path = require('path');

var app = express();

html_templates = __dirname + '/html_templates';

app.set('views', html_templates + '/views');
app.set('view engine', 'jade');

app.use('/Core', express.static(__dirname + '/Core'));


app.listen(3000, function () {
 console.log("express has started on port 3000");
});

require('./html_templates/controller/routes.js')(app);

有没有动态的方法来创建它?

7 个答案:

答案 0 :(得分:44)

我会为/modules/:name

做同样的事情
app.get('/article/:id', function(req , res){
  res.render('article' + req.params.id);
});

从休息的角度来看,这将更有意义。

如果您因任何特殊原因无法执行此操作,则可能需要执行以下操作:

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

这是你的意思吗?

答案 1 :(得分:14)

终于搞定了..

如果我得到了,第1条,第2条等:

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

如果我有多级网址,我创建了一个自定义功能:

function geturl(url) {

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

};

答案 2 :(得分:5)

有很多方法可以实现动态快速路由。它在很大程度上取决于你在项目中实现的结构,这里我留下一个动态路由的例子,我希望它会有用。

RouterService.js

 AGENT  CLIE
 -----------
 A         2
 B         2
 C         1

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

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

答案 3 :(得分:2)

以下是其他几个解决方案:

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

或使用app.all作为第一个解决方案或使用通用中间件:

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

答案 4 :(得分:0)

我创建了一个名为jadewalker的新模块。它会自动创建路由器代码。

我们只需在您的jadewalkerjade文件中添加pug条评论。

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

并将此模块添加到我们的app。这就是全部。

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

我们可以通过网址http://localhost:3000/b/abc访问我们的玉文件。 (^∀^)

答案 5 :(得分:0)

这是我创建动态API时所做的事情,而我可以控制哪些API允许访问哪些方法。要从现在开始维护API,您只需编辑API数组即可。

public class PizzaOrder {

    private String firstName;
    private int pizzaSizeInInches;    
    //add other fields

    private PizzaOrder(Builder builder){
        this.firstName=builder.firstName;
        this.pizzaSizeInInches=builder.pizzaSizeInInches;
        //set other fields
    }

    public static class Builder{
        private String firstName;
        private int pizzaSizeInInches;
        //add other fields

        public Builder(){
        }

        public Builder firstName(String firstName){
            this.firstName=firstName;
            return this;
        }

        public Builder pizzaSizeInInches(int pizzaSizeInInches) {
            this.pizzaSizeInInches = pizzaSizeInInches;
            return this;
        }

        //add other setter method like above

        public PizzaOrder build(){
            return new PizzaOrder(this);
        }          
    }

    public static Builder builder(){
        return new Builder();
    }

    public static void main(String args[]){
        PizzaOrder.builder()
                .firstName("sanjeev")
                .pizzaSizeInInches(10)
                .build();
    }
}

答案 6 :(得分:0)

这是我的项目

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

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