Koa的动态路线?

时间:2015-07-31 11:55:34

标签: node.js promise generator koa co

假设我有一系列看起来像这样的路线:

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)。我做错了什么?

1 个答案:

答案 0 :(得分:4)

经过一些修修补补,我已经设法通过这样做来获得上述代码:

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

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

相关问题