路由

Router 主要用来描述请求 URL 和具体承担执行动作的 Controller 的对应关系, 框架约定了 app/router.js 文件用于统一所有路由规则。

定义 Router

我们统一在 app/router.js 里面定义 URL 路由规则

// app/router.js
module.exports = app => {
  const { router, controller } = app
  router.get('/user/:id', controller.user.info)
}

然后在 app/controller 目录下实现 Controller

// app/controller/user.js
class UserController extends Controller {
  async info() {
    const { ctx } = this;
    ctx.body = {
      name: `hello ${ctx.params.id}`,
    };
  }
}

这样就完成了一个最简单的 Router 定义,当用户执行 GET /user/123user.js 这个里面的 info 方法就会执行。

Last updated