Building Web Services using Koa.js

Node.js has emerged as a powerful way to build web applications, web services, and many cross-platform applications. Node.js has empowered the developers across the globe to write a highly scalable, efficient, and complex cloud code to solve real-world computational problems. Developers can develop both frontend and backend systems separately and the hybrid one. There are many Node.js frameworks and libraries are available that empower the developer community to accelerate the custom website development solutionsKoa.js is one of the widely used frameworks to build Node.js applications. It is designed and maintained by the creators of well-known framework Express.js. Koa.js is a lightweight and flexible way to build web services which uses a thinner and efficient middleware system into the picture. Developers have the power to extend the existing features by using custom and already available modules into development. Below are the steps to kick start your Koa.js project:

Steps to start your Koa.js project

1. Developers can install the latest version of Node.js from https://nodejs.org or using Node Version Manager (NVM).

2. Open terminal, switch to the desired directory, run

npm init

and follow the steps.

3. After that run following command to install the Koa framework into your application

npm install koa --save

4. Create a file app.js and write the following code snippet:

const Koa = require('koa');
const app = new Koa();app.use( ctx =>
ctx.body = 'Hello World';
});
app.listen(3000);

5. Now try to run the code using

node app.js

You can see the output Hello World on the screen when you try to access http://localhost:3000

Have you noticed something written as ctx? ctx is the Koa context which is an object that binds the request and response in a single object. Now we need not to call res.end(). ctx.body enables the response to bind the response body and send it to the requesting client, i.e., ctx.body = ‘Hello World’ is the same as res.end(‘Hello World’)

The request and response objects can simply get from

app.use(ctx => {
let req = ctx.request; //Request object
let res = ctx.response; //Response object
});

Adding Custom Routes

Now, let's try to add a router in our code to see how the router works in Koa.js applications

1. Now add following code snippet to our app.js

const KoaRouter = require(‘koa-router’);
let router = new KoaRouter();
router.get('WelcomeRouter', '/', (ctx, next) => {
ctx.body = "My first welcome router";
});

Above code will declare and define the first router. Koa router has three parts: (a) router name, WelcomeRouter in our case, (b) Router Path, ‘/’ in the above code and (c) callback function having Koa context ctx and next as param arguments.

Now add the following code snippet to use our Koa Router in Koa object middleware:

app.use(router.routes());

Now our new code will become as follows:

const Koa = require('koa');
const app = new Koa();
const KoaRouter = require('koa-router');
let router = new KoaRouter();
app.use(router.routes())
router.get('WelcomeRouter', '/', (ctx, next) => {
ctx.body = “My first welcome router”;
});
app.listen(3000);

Now try to run the above code and see the output.

Koa routes also enable us to add a prefix in all the router path, if we need to differentiate the request URL paths. To do so, we just need to define prefix while creating out koa router object.

let router = new KoaRouter({
prefix:'/api'
});

After updating our code, all the request will have to be like http://localhost:3000/api/

Available Methods

Like Express.js routes, Koa Router is also being enriched with RESTful API paradigm. We can easily incorporate GET, POST, PUT, and DEL methods while creating our routes.

router.get('GetExample','/api/get, (ctx) => {
ctx.body = 'This is get request exampe';
});
router.post('PostExample','/api/post, (ctx) => {
ctx.body = 'This is post request exampe';
});
router.put('PutExample','/api/put, (ctx) => {
ctx.body = 'This is put request exampe';
});
router.del('DelExample','/api/del, (ctx) => {
ctx.body = 'This is Del request exampe';
});

We can also pass URI params like:

router.get('GetExample','/api/get/:id, (ctx) => {let id = ctx.params.id;
ctx.body = 'The Param Id is ' + id;
});

Similarly, request body can get as ctx.request.body

Middlewares

Similar to Express.js, Koa.js also has the functionality to use middlewares in our application. using the middleware is as same as that in Express.js apps. Following is an example snippet:

let custom_middleware_function = (ctx, next) => {
console.log('Some custom middleware');next();
}
app.use(custom_middleware_function);

Error Handling

Error handling is a vital part of any software programming. While deploying our application to a production environment, we have to make sure that our application is error-free and if any error occurs in the future, it must be able to handle the same without crashing or hampering end user’s experience. Like other languages, we can use a try-catch block in our Koa.js application. Though Koa.js also allows developers to handle errors in a custom way.

We can also handle http errors with response code as follows:

ctx.status = 404;

Adding above code will simply return Not Found error to the requested resource.

Request and Response aliases

There are following request and response aliases available in Koa.js

Request alias:

ctx.header
ctx.headers
ctx.method
ctx.method=
ctx.url
ctx.url=
ctx.originalUrl
ctx.origin
ctx.href
ctx.path
ctx.path=
ctx.query
ctx.query=
ctx.querystring
ctx.querystring=
ctx.host
ctx.hostname
ctx.fresh
ctx.stale
ctx.socket
ctx.protocol
ctx.secure
ctx.ip
ctx.ips
ctx.subdomains
ctx.is()
ctx.accepts()
ctx.acceptsEncodings()
ctx.acceptsCharsets()
ctx.acceptsLanguages()
ctx.get()

Response alias:

ctx.body
ctx.body=
ctx.status
ctx.status=
ctx.message
ctx.message=
ctx.length=
ctx.length
ctx.type=
ctx.type
ctx.headerSent
ctx.redirect()
ctx.attachment()
ctx.set()
ctx.append()
ctx.remove()
ctx.lastModified=
ctx.etag=

Conclusion

So, we have seen how we can give a kick start to our web services using Koa.js enabling our Node.js apps to have flexible, lightweight and scalable features.

Koa helps in developing a smaller, expressive, and more robust foundation for web apps and APIs. By making use of its features, Koa allows the web app to ditch callbacks and even increase the number of error-handling. Koa does not have middleware in its core but has a suite of methods that make writing servers fast. 

Signity Solutions offer outsource programming services opportunity to help build efficient web apps and APIs by using a number of helpful methods and accessors. We can even use various modules to extend and customize Koa.js according to the specific needs of your project.

 Ashwani Sharma

Ashwani Sharma