
- Koa.js 教程
- Koa.js - 主頁
- Koa.js - 概述
- Koa.js - 環境
- Koa.js - Hello,World!
- Koa.js - 生成器
- Koa.js - 路由
- Koa.js - url 生成
- Koa.js - http 方法
- Koa.js - 請求物件
- Koa.js - 響應物件
- Koa.js - 重定向
- Koa.js - 錯誤處理
- Koa.js - 級聯
- Koa.js - 模板
- Koa.js - 表單資料
- Koa.js - 檔案上傳
- Koa.js - 靜態檔案
- Koa.js - Cookie
- Koa.js - 會話
- Koa.js - 認證
- Koa.js - 壓縮
- Koa.js - 快取
- Koa.js - 資料庫
- Koa.js - RESTful API
- Koa.js - 日誌
- Koa.js - 腳手架
- Koa.js - 資源
- Koa.js 有用資源
- Koa.js - 快速指南
- Koa.js - 有用資源
- Koa.js - 討論
Koa.js - 路由
Web 框架在不同的路由上提供資源,例如 HTML 頁面、指令碼、影像等。Koa 在核心模組中不支援路由。我們需要使用 koa-router 模組輕鬆在 Koa 中建立路由。使用以下命令安裝此模組。
npm install --save koa-router
現在我們已安裝 koa-router,讓我們看一個簡單的 GET 路由示例。
var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); // Define routes function *getMessage() { this.body = "Hello world!"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000);
如果我們執行我們的應用程式並訪問 localhost:3000/hello,伺服器將在路由“/hello”接收到一個 GET 請求。我們的 Koa 應用程式執行附加到此路由的回撥函式,併發送“Hello, World!”作為響應。

我們還可以在同一路由有多個不同的方法。例如,
var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); _.post('/hello', postMessage); function *getMessage() { this.body = "Hello world!"; }; function *postMessage() { this.body = "You just called the post method at '/hello'!\n"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000);
要測試此請求,請開啟您的終端並使用 cURL 執行以下請求
curl -X POST "https://:3000/hello"

express 提供了一個特殊的方法all,使用相同函式在特定路由處理所有型別的 HTTP 方法。要使用此方法,請嘗試以下操作 -
_.all('/test', allMessage); function *allMessage(){ this.body = "All HTTP calls regardless of the verb will get this response"; };
廣告