1. Install koa-router module

Back to TOC

Go to your project folder and run:

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

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

2. Using koa-router

Back to TOC
There are many styles which you can implement the routing mechianism with koa-router. This tutorial will show 2 styles.

First style is called Express-style. This style is similiar to what express.js has offered. It enable the use of app.get, app.put, app.post, app.delete and etc.

Second style is what i called Middleware-style. This style allows you to instantiate a koa-router object, configure the route(s) on this object and output as middleware for app.use.

Both styles named URL parameters and regexp captures.

Style 1: Express-style

Back to TOC
Let’s enable app to be Express-style.

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

You console will show 3 lines of information:

2014-03-06T09:49:56.401Z - GET /
Express-style example
2014-03-06T09:49:57.076Z - GET /favicon.ico
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.
"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);

Note on route stacking*

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!

This is because all Koa routes run in stack. You have to make sure that the middleware you want all routes to use put on top of the rest.


Style 2: Middleware-style

Back to TOC
Now we create a new koa-router object and name it publicRouter, that means this set of routes will be accessible to public. We can create any number of router object as we need, one might call securedRouter for all routes that need to be authenticated before access.

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

You can configure as many route as you like.

app.use(publicRouter.middleware());
2014-03-06T23:11:20.447Z - GET /auth/github
Middleware-style Example
2014-03-06T23:11:21.164Z - GET /favicon.ico

3. Complete app.js

Back to TOC

"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);

4. Parameter & RegEx route

Back to TOC
koa-router supports route like parametered '/:category/:id' and regex '^/.*/?$'. The parameter can be retrieve by using this.params.


Download

Back to TOC
Download the project for this tutorial here:
https://github.com/Zev23/koa-tutorial-routing






Copyright © Zev23.com 2014 All Rights Reserved. No part of this website may be reproduced without Zev23.com’s express consent.

Post a Comment
Newer Post Older Post Home