Koa.js - URL Building



We can now define routes; they are either static or fixed. To use dynamic routes, we need to provide different types of routes. Using dynamic routes allow us to pass parameters and process based on them. Following is an example of a dynamic route.

var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router();

_.get('/:id', sendID);

function *sendID() {
   this.body = 'The id you specified is ' + this.params.id;
}

app.use(_.routes());
app.listen(3000);

To test this go to https://localhost:3000/123. You will get the following response.

URL Building ID

You can replace '123' in the URL with anything else and it'll be reflected in the response. Following is a complex example of the above.

var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router();

_.get('/things/:name/:id', sendIdAndName);

function *sendIdAndName(){
   this.body = 'id: ' + this.params.id + ' and name: ' + this.params.name;
};

app.use(_.routes());

app.listen(3000);

To test this go to https://localhost:3000/things/tutorialspoint/12345.

URL Building Complex

You can use the this.params object to access all the parameters you pass in the URL. Note that the above two have different paths. They will never overlap. Also if you want to execute the code when you get '/things', then you need to define it separately.

Pattern Matched Routes

You can also use regex to restrict URL parameter matching. Let's say you need the id to be five digits long number. You can use the following route definition.

var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router();

_.get('/things/:id([0-9]{5})', sendID);

function *sendID(){
   this.body = 'id: ' + this.params.id;
}

app.use(_.routes());
app.listen(3000);

Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a Not found message as response.

For example, if we define the same routes as above, on requesting with a valid URL, we get −

URL Matching Correct
Advertisements