Koa.js Router GET and POST Request Example in Node.js and Javascript Using Koa-router Library Full Project For Beginners

 

Welcome folks today in this blog post we will be building a koa.js router get and post request example using koa-router library in node.js and javascript.All the full source code of the application is shown below.

 

 

 

Get Started

 

 

npm install --save koa-router

 

In order to get started you need to make an index.js file and copy paste the following code

 

READ  How to Capture or Export HTML5 Canvas to GIF/JPG/PNG Images and PDF Documents in Browser Using Javascript Full Project For Beginners

 

index.js

 

 

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

var _ = router();              //Instantiate the router
_.get('/hello', getMessage);   // Define routes

function *getMessage() {
   this.body = "Hello world!";
};

app.use(_.routes());           //Use the routes defined using the router
app.listen(3000);

 

 

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

var _ = router(); //Instantiate the router

_.get('/hello', getMessage);
_.post('/hello', postMessage);

function *getMessage() {
    this.body = "Hello world!";
};
function *postMessage() {
   this.body = "You just called the post method at '/hello'!\n";
};
app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);

Leave a Reply