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(); //实例化路由器 _.get('/hello', getMessage); // 定义路由 function *getMessage() { this.body = "Hello world!"; }; app.use(_.routes()); //使用通过路由器定义的路由 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(); //实例化路由器 _.get('/hello', getMessage); _.post('/hello', postMessage); function *getMessage() { this.body = "Hello world!"; }; function *postMessage() { this.body = "You just called the post method at '/hello'!"; }; app.use(_.routes()); //使用通过路由器定义的路由 app.listen(3000);
要测试此请求,请打开终端并使用 cURL 执行以下请求
curl -X POST "https://localhost:3000/hello"
express 提供了一种特殊方法 all,可使用相同函数处理特定路由上的所有类型的 http 方法。要使用此方法,请尝试以下操作 −
_.all('/test', allMessage); function *allMessage(){ this.body = "All HTTP calls regardless of the verb will get this response"; };