美文网首页
Koa2 路由

Koa2 路由

作者: 叶叶叶xxx | 来源:发表于2020-04-21 14:50 被阅读0次

    第一步 引入koa 和 fs模块读取html用

    const Koa = require('koa')
    const app = new Koa()
    const fs = require('fs')
    
    //正常操作
    app.use(async (ctx) => {
        let url = ctx.request.url
        let html = await route(url)
        ctx.body = html
    })
    
    app.listen(3001, () => {
        console.log('router is listen port 3001..')
    })
    

    第二步新建几个页面

    第三步

    //这里没啥好说的
    async function route(url) {
        let page = '404.html'
        switch (url) {
            case '/':
                page = 'index.html'
                break
            case '/index':
                page = 'index.html'
                break
            case '/todo':
                page = 'todo.html'
                break
            case '/404':
                page = '404.html'
                break
            default:
                break
        }
        let html = await render(page)
        return html
    }
    
    function render(html) {
        //使用promise包一下处理一下异步
        return new Promise((resolove, reject) => {
            let pageUrl = `./page/${html}`
        //参数1:文件路径名,  参数2:二进制,  参数3:回调
            fs.readFile(pageUrl, "binary", (err, data) => {
                if (err) {
                    reject(err)
                } else {
                    resolove(data)
                }
            })
        })
    }
    
    

    使用koa-router

    npm 安装koa-router中间件

    npm install --save koa-router
    

    示例代码

    const Koa = require('koa')
    const Router = require('koa-router')
    
    const app = new Koa()
    const router = new Router({
        // 添加路由前缀层级
        prefix: '/cengji'
    })
    
    router
        .get('/', (ctx, next) => {
            ctx.body = 'Hello word'
        })
        .get('/todo', (ctx, next) => {
            ctx.body = 'Todo page'
        })
    
    
    app
        .use(router.routes())
        //router.allowedMethods() 推荐用法:router.allowedMethods()用在了路由匹配router.routes()之后
        // 所以在当所有路由中间件最后调用.此时根据ctx.status设置response响应头
        .use(router.allowedMethods())
    
    app.listen(3333, () => {
        console.log('app is starting at port 3333...')
    

    子路由

    const Koa = require('koa');
    const app = new Koa();
    const Router = require('koa-router');
    
    let aaa= new Router();
        aaa
            .get('/aaa',async(ctx)=>{
                ctx.body="aaa";
            })
            .get('/bbb',async(ctx)=>{
                ctx.body ='bbb';
            })
    
    let bbb= new Router();
          bbb
              .get('/aaa',async(ctx)=>{
                  ctx.body="aaa";
              })
              .get('/aaa',async(ctx)=>{
                  ctx.body ='bbb';
              })
            
    //装载所有子路由
    let router = new Router();
    router.use('/aaa',home.routes(),home.allowedMethods());
    router.use('/bbb',page.routes(),page.allowedMethods());
    
    //加载路由中间件
    app.use(router.routes()).use(router.allowedMethods());
    
    app.listen(3000,()=>{
        console.log('[demo] server is starting at port 3000');
    });
    

    相关文章

      网友评论

          本文标题:Koa2 路由

          本文链接:https://www.haomeiwen.com/subject/afbuihtx.html