KOA2 Series router

Posted by thewooleymammoth on Sun, 05 Apr 2020 04:45:04 +0200

Native route

In order to implement native routing, you need to get the path entered in the address bar, and then jump according to the different path. It can be realized by ctx.request.url and switch judgment.

app.use((ctx)=>{
    switch(ctx.url){
           case '/':
               console.log("You are accessing the root path");
               break;
           case '/index':
               console.log("You are visiting index Route");
               break;
           case '/todo':
               console.log("You are visiting todo Route");
               break;
           case '/404':
               console.log("There is no such path");
               break;
           default:
               break; 
       }
})

But this is far from meeting the business requirements, so we use the middleware koa router

Koa router Middleware

  1. Introduce middleware koa Router: const router = require ('koa router ');
  2. Use middleware koa Router: app.use(router.routes()).use(router.allowedMethods());

For instance

// add url-route:
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});

router.get('/', async (ctx, next) => {
    ctx.response.body = '<h1>Index</h1>';
});

Often we have a hierarchical concept when dealing with routes. For example, routes beginning with '/ home' are handed over to the sub route home for processing, and routes beginning with '/ sign' are handed over to the sub route sign for processing.

Hierarchical routing

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');


let home = new Router();
home.get('/jspang',async(ctx)=>{
    ctx.body="Home JSPang";
}).get('/todo',async(ctx)=>{
    ctx.body ='Home ToDo';
})

let sign = new Router();
sign.get('/jspang',async(ctx)=>{
    ctx.body="sign JSPang";
}).get('/todo',async(ctx)=>{
    ctx.body ='sign ToDo';
})

//Load all child routes
let router = new Router();
router.use('/home',home.routes(),home.allowedMethods());
router.use('/page',page.routes(),page.allowedMethods());

//Load routing Middleware
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000,()=>{
    console.log('[demo] server is starting at port 3000');
});

After using hierarchical routing, we can separate the business logic well.
But there is a new problem: all routes are written in the index.js file, which makes the code structure messy

To solve this problem, let's reorganize the code structure

Total route sub structure

As shown in the figure above, I have extracted all the routing codes from the router directory

Three js files are stored in the router directory

index.js  //Master routing table
sign.js   //Sub routing table sign
home.js   //Child routing table home

Code in index.js

const sign = require('./sign.js');
const home = require('./home.js');

module.exports = {
    sign,
    home
}

Code in sign.js

const Router = require('koa-router');
const sign = new Router();

sign.get('/',async(ctx)=>{
    await ctx.render('sign',{title:"sign"});
    if(ctx.cookies.get('place')){
        ctx.cookies.set('place','sign over');
    }else{
        ctx.cookies.set('place','sign');
    }
}).get('/cs',async(ctx)=>{
    ctx.body = "Sign cs";
});

module.exports = sign;

Entry file index.js

const Koa = require('koa');
const Router = require('koa-router');
const BodyParser = require('koa-bodyparser');
const Static = require('koa-static');
const views = require('koa-views');
const routers = require('./router');
const path = require('path');


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

//Using the template ejs
app.use(views(path.join(__dirname,'./views/'),{extension:'ejs'}));

//Routing table
app.use(router.routes()).use(router.allowedMethods());
router.use('/sign',routers.sign.routes(),routers.sign.allowedMethods());
router.use('/home',routers.home.routes(),routers.home.allowedMethods());

//post analysis
app.use(BodyParser());

//Black hole routing
app.use(Static(path.join(__dirname,'./static/')));

//Port monitoring
app.listen(80);

In this way, the structure is clear and the logic is clear

Reference articles
Technology fat blog