Routes are an important aspect to build any web application. However, KoaJS does not support routes as part of the core module. Therefore, we have to use an external module to enable routing. In this post, we will look at a basic Koa JS Router Example using the koa-router
package.
If you are totally new to KoaJS, I will recommend you to go through this post on getting started with KoaJS.
1 – Installation of KoaJS Router Package
Unlike ExpressJS, Koa does not come with in-built router handling capability.
However, assuming that you already have a KoaJS application, we only need to install another package to work with routers.
$ npm install koa-router
Once the package installation is complete, we are ready to tweak our application to utilize the koa-router
package.
2 – Implement a KoaJS Router Example
Let us implement a simple GET route example.
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const router = new Router();
router.get('/greetings', (ctx, next) => {
ctx.body = "Hello, World from Router"
});
app.use(router.routes())
app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});
Let us understand what is happening in the above example.
- We first import the necessary packages. This includes
koa
andkoa-router
. - Next, we create a Koa application instance using the constructor and
new
keyword. - Also, we create an instance of the
koa-router
. - Now, we can attach the route definitions to the router instance. For example, to attach a GET route, we call
router.get()
function. This function takes the route path as input and a callback function that contains the Koa application context. - Within the callback, we set the response body to the required greeting message.
- Moving on, we call
app.use()
to attach the route definitions to the KoaJS middleware stack. - Finally, we call
app.listen()
to start the application on port 3000.
Note here that the Koa Context is a special object that encapsulates the request
and response
objects of NodeJS into a single object. In KoaJS, a context instance is created per request and is referenced in the middleware as the receiver or the ctx
identifier.
If we start the application at this point and visit http://localhost:3000/greetings
, we will be able to see the greeting message in the browser.
Conclusion
We have successfully looked at a Koa JS Router Example using koa-router
middleware package. We also explore the concept of context in a KoaJS application.
Since the core KoaJS framework does not provide features such as router, the base framework is quite minimal. This makes it extremely flexible.
Want to create dynamic routes? Check out this post on how to handle route parameters in KoaJS.
If you have any comments or queries about this post, please feel free to mention them in the comments section below.
0 Comments