开发手册 欢迎您!
软件开发者资料库

Koa.js - 路由

Koa.js路由 - 从基本到高级概念的简单简单步骤学习Koa.js,其中包括概述,环境,Hello World,生成器,路由,URL构建,HTTP方法,请求对象,响应对象,重定向,错误处理,级联,表单数据,文件上传,模板,静态文件,Cookie,会话,身份验证,压缩,缓存,数据库,RESTful API,日志记录,脚手架,资源。

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 routesfunction *getMessage() {   this.body = "Hello world!";};app.use(_.routes());           //Use the routes defined using the routerapp.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 routerapp.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";};