【问题标题】:Dynamic routes in Koa?Koa中的动态路线?
【发布时间】:2015-10-23 02:22:38
【问题描述】:

假设我有一个如下所示的路线数组:

var routes = [
    {
        route: '/',
        handler: function* () { this.body = yield render('home', template.home) }
    },
    {
        route: '/about',
        handler: function* () { this.body = yield render('about', template.about) }
    }
];

app.use 他们的最佳方式是什么?我试过这样做(koa-route 作为我的中间件)是这样的:

Promise.each(routes, function(r) {
    app.use(route.get(r.route, r.handler));
}).then(function() {
    app.use(function *NotFound(next) {
        this.status = 404;
        this.body = 'not found';
    });
});

但它似乎不起作用(我也尝试过普通的routes.forEach)。我做错了什么?

【问题讨论】:

    标签: node.js promise generator koa co


    【解决方案1】:

    经过一番修改后,我设法通过这样做使上述代码正常工作:

    var routes = {
        '/': function* () { this.body = yield render('home', template.home); },
        '/about': function* () { this.body = yield render('about', template.about); }
    };
    
    app.use(function* respond() {
        if (routes[this.request.url])
            yield routes[this.request.url].call(this);
    });
    

    我会尽可能接受这个答案,但如果有人发布更好的解决方案,我会很乐意接受他们的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2021-06-29
      • 2019-07-19
      • 2011-08-19
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      相关资源
      最近更新 更多