路由(Router)
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);
};
Controller
//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/123
,
user.js
這個裡面的 info 方法就會執行。