Thursday, March 6, 2014

Koajs Tutorial - Routing

Koa has just so many options to perform routing for your application. This tutorial will focus on the use of koa-router.

Before begin


1. Install koa-router module

Back to TOC

Go to your project folder and run:

npm install koa-router
  • Load the module by adding code below to existing app.js.
...
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.

  • Add the code after the line app.use(reqlogger);
app.use(Router(app));
  • Create a GET route to '/' after that.
app.get('/', function *(){
  console.log('Express-style example');
  this.body = "This is root page ('/')";
});
  • Save and start your server node --harmony app.js.

  • Open your browser and go to localhost:3000, you will see the message as the one defined in the example on both browser and console.

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.
  • Content for app.js till now:
"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*

  • If you try rearrange your codes in this order:
app.use(Router(app)); //This is now the top most
app.use(reqlogger);
app.get('/',...
  • This is what you will see in the console log:
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.

  • Create a new public Router.
const publicRouter = new Router();
  • Configure a Get route /auth/github. We will implement the actual authentication in another tutorial.
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.

  • Let the application use it as middleware.
app.use(publicRouter.middleware());
  • Restart your application.

  • Go to localhost:3000/auth/github and check your server log.
    You should see somethine like this:

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.

No comments: