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!”作為響應。

Routing Hello

我們還可以在同一路由有多個不同的方法。例如,

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"

Curl Routing

express 提供了一個特殊的方法all,使用相同函式在特定路由處理所有型別的 HTTP 方法。要使用此方法,請嘗試以下操作 -

_.all('/test', allMessage);

function *allMessage(){
   this.body = "All HTTP calls regardless of the verb will get this response";
};
廣告