假设我有一组如下所示的路线:
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
)。我做错了什么?
最佳答案
经过一些修改,我成功地通过这样做使上述代码正常工作:
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);
});
我会尽可能接受这个答案,但如果有人发布更好的解决方案,我会很乐意接受他们的。
关于node.js - 科阿的动态路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31745598/