Koa.js Tutorial to Extract Query Params or Paramters From URL Using Koa-router Library Full Example For Beginners

 

Welcome folks today in this blog post we will be extracting query params or parameters from url 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 following library using the npm command as shown below

 

npm i koa-router

 

After 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('/:id', sendID);

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

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

 

See also  Deno.js Tutorial to Validate JSON Objects Schema Using simplejsonvalidator Library in Node.js & TypeScript Full Project For Beginners

 

And now if you execute the script you will see the query parameter printed in the form of 123 printed on the screen

 

Extracting Multiple query params

 

 

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

Leave a Reply