Koajs-routing

提供:Dev Guides
移動先:案内検索

Koa.js-ルーティング

Webフレームワークは、HTMLページ、スクリプト、画像などのリソースを提供します。 異なるルートで。 Koaは、コアモジュールのルートをサポートしていません。 Koaでルートを簡単に作成するには、Koa-routerモジュールを使用する必要があります。 次のコマンドを使用してこのモジュールをインストールします。

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://localhost:3000/hello"

カールルーティング

同じ関数を使用して特定のルートですべてのタイプのhttpメソッドを処理するために、特別なメソッド all がexpressによって提供されます。 この方法を使用するには、次を試してください-

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

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