Koa2常用的一些中间件

koa-bodyparser 功能:解析请求体

代码实现

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
app.use(bodyParser());

app.use(async ctx => {
  //可以获取到request.body
  ctx.body = ctx.request.body;
});

koa-static 功能:处理静态资源

代码实现

const Koa = require('koa')
const static = require('koa-static')

const app = new Koa()

const staticPath = './static'

//即可直接通过'./static',访问到静态资源
app.use(static(
  path.join(__dirname, staticPath)
))

app.listen(3000, () => {
  console.log('端口号是 3000')
})

koa-router 功能:路由

代码实现

const Koa = require('koa');
const Router = require('koa-router');
 
const app = new Koa();
const router = new Router();
 
//实现 '/'、'/koa'两个路由层级
router
    .get('/',(ctx,next)=>{
        ctx.body="Index page";
    })
    .post('/koa',(ctx,next)=>{
        ctx.body="Koa page";
    });
 
app
  .use(router.routes())
  .use(router.allowedMethods());
  
app.listen(3000,()=>{
    console.log('端口号是 3000');
});

koa-jwt搭配jsonwebtoken 功能:实现jwt鉴权

代码实现

const koa = require('koa');
const koajwt = require('koa-jwt');
const jsonwebtoken = require('jsonwebtoken');
const util = require('util');
const koabody = require('koa-body');
const app = new koa();

const SECRET = 'shared-secret'; // demo,可更换

app.use(koabody());

// 中间件对token进行验证
app.use(async (ctx, next) => {
    // let token = ctx.header.authorization;
    // let payload = await util.promisify(jsonwebtoken.verify)(token.split(' ')[1], SECRET);
    return next().catch((err) => {
        if (err.status === 401) {
            ctx.status = 401;
            ctx.body = {
                code: 401,
                msg: err.message
            }
        } else {
            throw err;
        }
    })
});

app.use(koajwt({ secret: SECRET }).unless({
    // 登录接口不需要验证
    path: [/^\/api\/login/]
}));

// 示例
const USER = {
    username: 'zhangsan',
    password: '123456',
    id: 100
}
// 登录接口签发token, 为了简便不使用router
app.use(async (ctx, next) => {
    if (ctx.path === '/api/login' && ctx.method === 'POST') {
        // 登录
        // 判断用户名密码是否匹配
        let checkUser = ctx.request.body.username == USER.username && ctx.request.body.password == USER.password;
        if (checkUser) {
            ctx.body = {
                code: 200,
                msg: '登录成功',
                token: jsonwebtoken.sign(
                    { name: USER.username, id: USER.id },  // 加密userToken
                    SECRET,
                    { expiresIn: '1h' }
                )
            }
        } else {
            // 登录失败, 用户名密码不正确
            ctx.body = {
                code: 400,
                msg: '用户名密码不匹配'
            }
        }
    } else if (ctx.path === '/api/user' && ctx.method === 'GET') {
        // 获取用户信息
        // 中间件统一验证token
        ctx.body = {
            code: 200,
            data: USER,
            msg: '请求成功'
        }
    }
})
app.listen(3000,()=>{
    console.log('端口号是 3000');
});

koa-multer 功能:上传文件

代码实现

const Koa = require('koa');
const Router = require('koa-router');
const multer = require('koa-multer');
const path = require('path');

const app = new Koa();

let storage = multer.diskStorage({
    destination: path.resolve('upload'),
    filename: (ctx, file, cb)=>{
        cb(null, file.originalname);
    }
});
let fileFilter = (ctx, file ,cb)=>{
//过滤上传的后缀为txt的文件
    if (file.originalname.split('.').splice(-1) == 'txt'){
        cb(null, false); 
    }else {
        cb(null, true); 
    }
}
let upload = multer({ 
  storage: storage,
  fileFilter: fileFilter 
});

let router = new Router();
router.post('/upload', upload.single('file'), async ctx => {
    if (ctx.req.file){
        ctx.body = 'upload success';
    } else {
        ctx.body = 'upload error';
    }
});
app.use(router.routes());

app.listen(3000,()=>{
    console.log('端口号是 3000');
});

你可能感兴趣的:(node)