Koa 2 first experience (2)

Posted by czambran on Tue, 24 Dec 2019 21:43:03 +0100

Koa2 routing

Implementation of Koa2 native routing

The role of routing in the web is self-evident. To realize the native routing, you need to go to the path entered in the address bar, and then jump according to the different path. In Koa2, we can use ctx.request.url to get access path:

const Koa = require('koa')
const app = new Koa()

app.use(async(ctx) => {
    const url = ctx.request.url
    ctx.body = url 
})

app.listen(3000, () => {
    console.log('demo3 is run')
})

Our file structure is as follows:

├── demo3.js
├── package.json
└── view
    ├── register.html
    ├── index.html
    └── login.html

We can implement the native route in this way:

const Koa = require('koa')
const fs = require('fs')
const app = new Koa()

function render(page) {
    return new Promise((resolve, reject) => {
        let viewUrl = `./view/${page}`
        fs.readFile(viewUrl, "binary", (err, data) => {
            console.log(1)
            if (err) {
                reject(err)
            } else {
                resolve(data)
            }
        })
    })
}
async function route(url) {
    let view = '404.html'
    switch(url) {
        case '/':
            view = 'index.html'
            break
        case '/login':
            view = 'login.html'
            break
        case '/register':
            view = 'register.html'
            break
        case '/index':
            view = 'index.html'
            break
        default:
            break
    }
    let html = await render(view)
    return html
}

app.use(async(ctx) => {
    const url = ctx.request.url
    let html = await route(url)
    ctx.body = html
})

app.listen(3000, () => {
    console.log('demo3 is run')
})

Through the above code, we have successfully implemented a routing switching function, but this writing is undoubtedly not elegant enough, and only in principle, not enough to deal with the problems encountered in our daily development. So we still need to introduce middleware to achieve our goal as before.

koa-router

First, we need to download the koa router middleware:

cnpm i koa-router --save

Then we can use koa router to exchange routes gracefully:

const Koa = require('koa')
const fs = require('fs')
const app = new Koa()
const Router = require('koa-router')
let home = new Router()

home.get('/', async ( ctx ) => {
    let html = `
        <ul>
            <li><a href="/page/helloworld">/page/helloworld</a></li>
            <li><a href="/page/404">/page/404</a></li>
        </ul>
    `
    ctx.body = html
})
// Subrouter 2
let page = new Router()
page.get('/404', async ( ctx )=>{
    ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
ctx.body = 'helloworld page!'
})
// Load all child routes
let router = new Router()
router.use('/', 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('demo4 is run')

 



By srtian
Link: https://www.jianshu.com/p/71a74c53a225
Source: Jianshu
The copyright of the brief book belongs to the author. For any reprint, please contact the author for authorization and indicate the source.

Topics: JSON