2

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

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

但这似乎不起作用(我也尝试过 plain routes.forEach)。我究竟做错了什么?

4

1 回答 1

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

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

于 2015-07-31T13:56:28.553 回答