2.koa路由

原生koa路由

index.js

const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
const path =require('path');
/**
 *
 *
 * @param {*} page html文件名称
 * @returns
 */
function render(page){
    return new Promise((resolve,reject)=>{
        let viewUrl =path.resolve(__dirname+`/${page}`);
        fs.readFile(viewUrl,'binary',(err,data)=>{
            if(err){
                reject(err)
            }else{
                resolve(data)
            }
        })
    })
}

async function route(url){
    let view = 'index.html'
    switch(url){
        case '/':
            view = 'index.html'
            break
        case '/index':
            view = 'index.html'
            break
        case '/todo':
            view = 'todo.html'
            break
        case '/404':
            view = '404.html'
            break
        default:
            break
    }
    let html = await render(view)
    return html
}
//app.use 两种方式的中间件,使用的是async方法(ctx,next)
app.use(async(ctx)=>{
    let url = ctx.request.url;
    let html = await route(url);
    ctx.body = html;
})

app.listen(3000);
console.log('starting at port 3000')

index.html




    
    
    
    index


    

koa2 demo index page

this is a index page

koa-router中间件

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

const Router = require('koa-router')

let home = new Router()

// 子路由1
home.get('/', async ( ctx )=>{
  let html = `
    
  `
  ctx.body = html
})

// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
  ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
  ctx.body = 'helloworld page!'
})

// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())

// 加载路由中间件
app.use(router.routes());
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('[demo] route-use-middleware is starting at port 3000')
})

//我们可以看到router.allowedMethods()用在了路由匹配router.routes()之后,所以在当所有路由中间件最后调用.
//只有当请求路径匹配到了/page才会执行allowedMethods

你可能感兴趣的:(2.koa路由)