目录

Koa.js - 路由( Routing)

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 app执行附加到此路由的回调函数并发送“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"

卷曲路由

express提供了一种特殊方法,用于使用相同的函数处理特定路径上的所有类型的http方法。 要使用此方法,请尝试以下方法 -

_.all('/test', allMessage);
function *allMessage(){
   this.body = "All HTTP calls regardless of the verb will get this response";
};
↑回到顶部↑
WIKI教程 @2018