美文网首页
2019-08-15 koa各种小知识

2019-08-15 koa各种小知识

作者: DreamNeverDie | 来源:发表于2019-08-15 22:44 被阅读0次

    1

    const Koa=require('koa');
    const mysql =require('promise-mysql');
    
    const server=new Koa();
    server.use(async (ctx, next)=>{   //koa只能用use,没有get,post方法,而是要用koa-router
                             //use只有一个参数,那就中间件函数       
        let db = await mysql.createPool({
            host:'localhost',
            user:'root',
            password:'123456',
            database:'computer'
        })
    
        let data=await db.query('update user_table set name=? where id=?',['dream1','2'])
        ctx.body=data
    });
    server.listen(3000)
    
    const Koa=require('koa')
    const fs=require('promise-fs')
    
    const server=new Koa()
    server.use(async (ctx,next)=>{
        const txt=await fs.readFile("./1.txt")
        ctx.txt=txt.toString()
        await next()
    })
    
    server.use(async (ctx,next)=>{
        await fs.appendFile('./log.txt',`[${new Date().toGMTString()}] ${ctx.method} ${ctx.url}\n`)
        await next()
    })
    
    server.use((ctx,next)=>{
        ctx.body=ctx.txt
    })
    
    server.listen(3000)
    
    1. koa-better-body 和ctx.redirect()重定向的使用
    const Koa=require('koa')
    const Router=require('koa-router')
    const fs=require('promise-fs')
    const bodyParser=require('koa-better-body')
    
    const server=new Koa()
    const router=new Router();
    
    let login=false;
    server.use(bodyParser())
    server.use(async (ctx,next)=>{
        await next()
    })
    
    server.use(router.routes())
    
    router.get('/',(ctx,next)=>{
        console.log(111)
    
        if(!login){
            console.log(222)
            ctx.redirect('/login')
    
        }
         console.log(444)
        ctx.body="欢迎"
    })
    
    router.get('/login',async (ctx,next)=>{
        const data=await fs.readFile('./static/login.html')
        ctx.body=data.toString()
    })
    
    router.post('/login',(ctx,next)=>{
        console.log(123)
        console.log(ctx.request.fields)
        login=true
        ctx.redirect('/')
    })
    
    server.listen(3000)
    
    1. koa下载文件,自定义文件名称
    const Koa=require('koa')
    const Router=require('koa-router')
    const fs=require('promise-fs')
    
    const server=new Koa();
    const router=new Router()
    
    router.get('/download', async (ctx,next)=>{
        ctx.attachment("ltf.txt")
        const data=await fs.readFile('./static/login.html')
        ctx.body=data
        
    })
    
    server.use(router.routes())
    
    server.listen(3000)
    

    4.下载的文件由程序动态指定内容就要用内存流

    const Koa=require('koa');
    const Router=require('koa-router');
    const fs=require('promise-fs');
    const MemoryStream=require('memorystream');
    
    let server=new Koa();
    server.listen(8080);
    
    let router=new Router();
    
    router.get('/b', async ctx=>{
      let stream=new MemoryStream();
      ctx.attachment('20170813.txt');
      ctx.body=stream;
    
      stream.write('aaa');
      stream.write('bbb');
    
      stream.end();
    });
    
    server.use(router.routes());
    
    

    5 操作http的头信息

    const Koa=require('koa');
    const Router=require('koa-router');
    const fs=require('promise-fs');
    const MemoryStream=require('memorystream');
    
    let server=new Koa();
    server.listen(8080);
    
    let router=new Router();
    
    router.get('/', async ctx=>{
      //console.log(ctx.headers);
      //console.log(ctx.headers['host']);
      //console.log(ctx.get('host'));
    
      ctx.set('name', 'blue');
      ctx.set('age', '18');
      ctx.set('set-cookie', 'type=12');
    
      ctx.body='welcome';
    });
    
    server.use(router.routes());
    
    

    6.下载大文件的时候返回流给body就行

    const Koa=require('koa');
    const Router=require('koa-router');
    const fs=require('promise-fs');
    const MemoryStream=require('memorystream');
    
    let server=new Koa();
    server.listen(8080);
    
    let router=new Router();
    
    router.get('/', async ctx=>{
      ctx.attachment('aaa.txt');
    
      // ctx.body=await fs.readFile('static/1.txt');
      ctx.body=await fs.createReadStream('static/1.txt');
    });
    
    server.use(router.routes());
    
    

    7 koa向第三方网站请求数据

    const Koa=require('koa');
    const request=require('./libs/request');
    
    let server=new Koa();
    server.listen(8080);
    
    // http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]
    
    server.use(async ctx=>{
      let url=`http://ip.taobao.com/service/getIpInfo.php?ip=202.13.96.75`;
    
      try{
        let data=await request(url);
        let json=JSON.parse(data.toString());
    
        ctx.body=json;
      }catch(e){
        ctx.body='地址解析失败';
      }
    });
    
    
    
    //request.js文件
    const http=require('http');
    
    module.exports=function (url){
      return new Promise((resolve, reject)=>{
        let req=http.request(url, res=>{
          let arr=[];
    
          res.on('data', data=>{
            arr.push(data);
          });
          res.on('end', ()=>{
            let buffer=Buffer.concat(arr);
    
            resolve(buffer);
          });
        });
        req.end();
    
        req.on('error', err=>{
          reject(err);
        });
      });
    };
    
    
    1. koa-static静态资源访问,设置缓存有效时间,
    const Koa=require('koa')
    const static=require('koa-static')
    const Router=require('koa-router')
    
    let server=new Koa();
    
    server.listen(8080);
    
    let router=new Router()
    
    router.all(/\.(jpg|png|gif)$/i,static('./static',{
      maxage:60*86400*1000
    }))
    
    router.all(/\.js$/i,static('./static',{
      maxage:1*86400*1000
    }))
    
    router.all(/\.css$/i,static('./static',{
      maxage:7*86400*1000
    }))
    
    router.all(/\.html?$/i,static('./static',{
      maxage:1*86400*1000
    }))
    
    router.all('*',static('./static',{
      maxage:7*86400*1000
    }))
    
    server.use(router.routes())
    /* 
    server.use(static('./static',{
      maxage:60*86400*1000,
      index:'index.html',//当别人访问/的时候
    }))
     */
    
    1. koa图片上传封装
    const Koa = require('koa')
    const Router = require('koa-router')
    const static = require('koa-static')
    const fs = require('promise-fs')
    const upload = require('./lib/upload')
    const path=require('path')
    
    const server = new Koa()
    const router = new Router()
    
    router.post('/upload', ...upload({
         async success(ctx) {
            ctx.body = { e: 'suc' }
        }, async failed (err) {
            if (err == 'maxfilesize exceeded') {
                ctx.status = 406  //可以覆盖upload.js里面的
                ctx.body = { e: 'error', msg: '文件过大' }
            }else{
                ctx.body={e:"error",msg:"服务器错误"}
            }
        },
        path:path.resolve(__dirname,'upload'),
        maxFileSize:100*1024
    }))
    
    
    server.use(router.routes())
    
    server.use(static('./static', {
        maxage: 7 * 3600 * 24 * 1000,
        index: 'form.html'
    }))
    
    server.listen(8080)
    
    
    //  lib/upload.js
    const convert=require('koa-convert')
    const body=require('koa-better-body')
    module.exports=function(options){
        return [async(ctx,next)=>{
            try{
              await next()
            }catch(e){
              if(e.message.startsWith('maxFileSize exceeded')){
                  ctx.status=406
                  options.failed &&await options.failed(ctx,'maxfilesize exceeded')
              }
              else{
                  ctx.status=500
                  ctx.body={e:"error",msg:"服务器错误"}
                  options.failed && await options.failed(ctx,'server error')
              }
            }      
          },convert(body({
            uploadDir:options.path,
            maxFileSize:options.maxFileSize
          })),async (ctx,next)=>{
              console.log(ctx.request)
            options.success&&await options.success(ctx)
        }]
    }
    

    相关文章

      网友评论

          本文标题:2019-08-15 koa各种小知识

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