Koa.js Tutorial to Implement Pattern Matching Routes and Query Params Using Regex (Regular Expression) Using koa-router Library in Node.js Full Example For Beginners

 

Welcome folks today in this blog post we will be implementing pattern matching routes and query params using regex (regular expression) using koa-router library. All the full source code of the application is shown below.

 

 

Get Started

 

 

 

In order to get started you need to install the below library using the npm command as shown below

 

npm i koa-router

 

After installing this make a index.js file and copy paste the following code

 

 

index.js

 

 

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

Leave a Reply