1.

What Is Koa.js Routing?

Answer»

Web frameworks PROVIDE resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the koa-router module to easily create routes in koa. Install this module using:

NPM install --save koa-router

Now that we have koa-router installed, lets look at a simple GET route example:

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

If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello", our koa app executes the callback function attached to this route and sends "Hello World!" as the RESPONSE.

Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the koa-router module to easily create routes in koa. Install this module using:

npm install --save koa-router

Now that we have koa-router installed, lets look at a simple GET route example:

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

If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello", our koa app executes the callback function attached to this route and sends "Hello World!" as the response.



Discussion

No Comment Found