How to use koa router to define a default?

by darrion.kuhn , in category: Javascript , 4 months ago

How to use koa router to define a default?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 4 months ago

@darrion.kuhn 

To define a default route in the Koa Router, follow these steps:

  1. Install the required dependencies:
1
npm install koa koa-router


  1. Import the necessary modules:
1
2
3
4
5
const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();


  1. Define your routes:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Define your default route
router.get('/', (ctx, next) => {
  ctx.body = 'Default route';
});

// Define other routes
router.get('/users', (ctx, next) => {
  ctx.body = 'Users route';
});
router.get('/products', (ctx, next) => {
  ctx.body = 'Products route';
});


  1. Define the default route at the end of your route definitions:
1
2
3
router.get('(.*)', (ctx, next) => {
  ctx.body = 'Invalid route';
});


  1. Use the router middleware in your Koa app:
1
2
3
app
  .use(router.routes())
  .use(router.allowedMethods());


  1. Start the server:
1
2
3
app.listen(3000, () => {
  console.log('Server running on port 3000');
});


With this setup, if a user visits the root URL '/', they will see the message 'Default route'. If a user visits a route that is not defined, they will see the message 'Invalid route'. Other specific routes like '/users' or '/products' can be defined as needed.


Note: The default route (.*) should be defined at the end of the route definitions to catch any undefined routes.