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


Curl Routing

特殊方法所有由express提供,用于处理所有类型的使用相同函数的特定路由的http方法.要使用此方法,请尝试以下 :

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

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