Google News
logo
Koa.js - Interview Questions
How does Koa.js handle routing?
Koa.js does not have built-in routing capabilities as part of its core functionality. Unlike some other web frameworks, such as Express.js, Koa.js intentionally avoids including a router in its core design philosophy. Instead, Koa.js gives developers the freedom to choose and integrate their preferred routing solution. This design approach contributes to the framework's minimalistic and modular nature.

To handle routing in Koa.js, developers often use external routing libraries. One popular choice is the koa-router library, which is specifically designed for routing in Koa.js applications.

Here's a basic overview of how routing is typically handled using koa-router:

Install koa-router : Begin by installing the koa-router library using npm or yarn.
npm install koa-router?

Import and Use koa-router :

* Import the koa-router module and create a router instance. Then, use the router to define routes and their associated middleware.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();?

Define Routes and Middleware :

* Use the router instance (router) to define routes and associate them with middleware functions. These middleware functions will be executed when a matching route is requested.
router.get('/', async (ctx) => {
  ctx.body = 'Hello, Koa!';
});

router.get('/about', async (ctx) => {
  ctx.body = 'About Page';
});?
Use the Router Middleware :

* To integrate the router with your Koa.js application, use the router's middleware function. This should be done after all route definitions.
app.use(router.routes());
app.use(router.allowedMethods());?

The router.routes() middleware handles route matching and invokes the appropriate route handlers, while router.allowedMethods() responds with the appropriate HTTP status for unsupported methods.

Here's a complete example :
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();

// Define routes and middleware
router.get('/', async (ctx) => {
  ctx.body = 'Hello, Koa!';
});

router.get('/about', async (ctx) => {
  ctx.body = 'About Page';
});

// Use the router middleware
app.use(router.routes());
app.use(router.allowedMethods());

// Start the Koa.js application
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});?

In this example, the koa-router library is used to define two routes: '/' and /about. The associated middleware functions handle the logic for each route. The app.use(router.routes()) line integrates the router into the Koa.js application, making it capable of handling incoming requests based on the defined routes.
Advertisement