[koa系列-2]路由

1、KICK OFF KOA - 2 : Route

本文继续KICK OFF KOA 的教程展开,学习第二课 路由

Step 1:获得提示

在命令行中输入kick-off-koa ,并选择第二个 Routing

kick-off-koa  

按下回车就能出现提示;

Step 2:编写代码

将下列代码保存成 koa2.js 文件:

var koa = require('koa');  
var app = koa();  
var port = process.argv[2];  
app.use(function*(next){  
  switch(this.path){
    case '/':
      this.body = 'hello koa';
      break;
    case '/404':
      this.body = 'page not found';
      break;
    case '/500':
      this.body = 'internal server error';
      break;
    default:
      return yield next;
  }
});

app.listen(port);  
  • this.path :用于获取路由完整路径,大伙儿可以自行尝试一下 this.method this.query以及 this.host 变量
  • 使用 switch语句 进行路由判断

其实所有的路由基本都是对上面的一次封装产生的;

Step 3:验证结果 运行:

kick-off-koa verify koa2.js  

如果不出意外,将展示成功。官方给出的答案是:

    var koa = require('koa');

    var app = koa();

    app.use(function* (next) {
      if (this.path !== '/') {
        return yield next;
      }

      this.body = 'hello koa';
    });

    app.use(function* (next) {
      if (this.path !== '/404') {
        return yield next;
      }

      this.body = 'page not found';
    });

    app.use(function* (next) {
      if (this.path !== '/500') {
        return yield next;
      }

      this.body = 'internal server error';
    });

    app.listen(process.argv[2]);

2、安装路由模块

在实际应用中,可以直接使用业界的插件,比如 koa-route

npm install koa-router  

然后在文件中正常引入即可:

...
const  
  Router = require('koa-router'),

  koa = require('koa'),
... 

此外可以使用的route中间件还有 koa-route koa-router koa-resource-router

3、使用路由模块

有多种方式使用路由模块,这里展现两种:

  1. Express-style,用法来自于express框架,它能够开启app.get, app.put, app.post,app.delete等功能
  2. Middleware-style,此时将 实例化 一个 koa-route 对象,在这个对象中配置路由规则,然后作为一个中间件塞入到app.use方法中。

3.1、Express-style

核心代码就一句:

app.use(Router(app));  

然后就可以按express风格路由了:

app.get('/', function *(){  
  console.log('Express-style example');
  this.body = "This is root page ('/')";
});

附上完成的示例程序:

"use strict"

const  
  Router = require('koa-router'),

  koa = require('koa'),
  app = koa();


//Middleware: request logger
function *reqlogger(next){  
  console.log('%s - %s %s',new Date().toISOString(), this.req.method, this.req.url);
  yield next;
}
app.use(reqlogger);

app.use(Router(app));

app.get('/', function *(){  
  console.log('Express-style example');
  this.body = "This is root page ('/')";
});

app.use(function *(){  
  this.body = 'Hello World';
});

app.listen(3000);  

Step 2:运行 node --harmony app.js,然后访问localhost:3000

控制台输出:

2014-03-06T09:49:56.401Z - GET /  
Express-style example  
2014-03-06T09:49:57.076Z - GET /favicon.ico  

注意页面里出现的文字是“This is root page ('/')”,而不是“Hello world ”

解释如下:

First line GET /
    Request Logger middleware returned the method and url.

Second line Express-style example
    The message from app.get('/',...) route.

Third line GET /favicon.ico
    Auto request from browser to get the fav icon. You won’t see this if using curl to test.

这里需要注意代码顺序。如果将代码顺序修改成:

app.use(Router(app)); //This is now the top most  
app.use(reqlogger);  
app.get('/',...  

那么控制台会是:

    Express-style example
    2014-03-06T09:49:57.076Z - GET /favicon.ico

Get /is missing!

这是因为 reqlogger 里面有 yield next,而router实例里面没有。 所以需要监听所有路由的中间件,应当放在这句 app.use(Router(app)); 前面。

3.2、Middleware-style

下面我们将创建名为publicRouterkoa-route对象,我们可以在程序里创建多个路由,用于不同的目的,比如用于身份验证。

Step 1:创建

const publicRouter = new Router();  

Step 2:配置路由“/auth/github”

publicRouter.get('/auth/github', function *(){  
  console.log("Middleware-style Example");
  this.body = "Authenticate with GitHub OAUTH API (Coming Soon)";
});

你可以继续按这种形式配置多个路由

Step 3:注册中间件

app.use(publicRouter.middleware());  

Step 4:运行并查看结果

完整的代码:

"use strict"

const  
  Router = require('koa-router'),

  koa = require('koa'),
  app = koa();


//Middleware: request logger
function *reqlogger(next){  
  console.log('%s - %s %s',new Date().toISOString(), this.req.method, this.req.url);
  yield next;
}
app.use(reqlogger);

app.use(Router(app));

app.get('/', function *(){  
  console.log('Express-style example');
  this.body = "This is root page ('/')";
});

const publicRouter = new Router();

publicRouter.get('/auth/github', function *(){  
  console.log("Middleware-style Example");
  this.body = "Authenticate with GitHub OAUTH API (Coming Soon)";
});

app.use(publicRouter.middleware());


app.use(function *(){  
  this.body = 'Hello World';
});

app.listen(3000);  

访问 localhost:3000/auth/github 将在控制台看到如下信息:

2015-04-03T06:25:04.691Z - GET /auth/github  
Middleware-style Example  
2015-04-03T06:25:04.904Z - GET /favicon.ico  

4、路由参数和正则

koa-route模块所建立的路由,支持类似与/:category/:id这样的参数路由,以及^/.*/?$正则匹配,可以通过this.params获取这些参数。

将上面的publicRouter的路由规则修改成:

publicRouter.get('/:name/:way', function *(){  
    console.log("Middleware-style Example",this.params);
    this.body = "Authenticate with GitHub OAUTH API (Coming Soon)";
});

重新运行程序后, 访问localhost:3000/auth/github 将在控制台看到如下信息:

2015-04-03T06:34:10.776Z - GET /auth/github  
Middleware-style Example [ name: 'auth', way: 'github' ]  
2015-04-03T06:34:11.030Z - GET /favicon.ico  

5、参考文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值