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 allows us to pass parameters and processes 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.
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 −
Next Topic:-Click Here
Pingback: Koa.js - Routing - Adglob Infosystem Pvt Ltd