node.js - 科阿的动态路线?

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

最佳答案

经过一些修改,我成功地通过这样做使上述代码正常工作:

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/

相关文章:

javascript - 访问 socket.io 回调函数外部的变量

javascript - browserify 'Error: Cannot find module' 试图修复 'Uncaught reference error: require is not defined'

尽管 Promise.resolve() ,Promise catch block 中的 Javascript 重试异步函数始终运行

javascript - 无法在 jquery ajax 中实现延迟 promise

python - 继续直到所有迭代器完成 Python

node.js - 当前端取消请求时,如何让 Express.js 中止 MongoDB 请求?

javascript - 问题删除用户模型(数组)中的项目,不确定如何保存结果

javascript - 在 nodejs 中重做任务,如果 promise 失败直到达到 maxLimit

python - 装饰一个产生的函数

ruby-on-rails - Rails 迁移引用的命名约定