@darrion.kuhn
To define a default route in the Koa Router, follow these steps:
- Install the required dependencies:
1
|
npm install koa koa-router
|
- 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();
|
- 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';
});
|
- Define the default route at the end of your route definitions:
1
2
3
|
router.get('(.*)', (ctx, next) => {
ctx.body = 'Invalid route';
});
|
- Use the router middleware in your Koa app:
1
2
3
|
app
.use(router.routes())
.use(router.allowedMethods());
|
- 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.