Koa2之中间件

1、koa-router 实现路由

2、koa-bodyparser 获取请求携带的请求体:ctx.request.body (不支持form格式)

3、koa-json-error 错误处理

[https://www.npmjs.com/package/koa-json-error]

npm install koa-json-error --save

const error = require('koa-json-error')
app.use(error())

4、koa-parameter 校验参数,放置在koa-bodyparser之后

[https://www.npmjs.com/package/koa-parameter]

npm install koa-parameter --save

const parameter = require('koa-parameter')
app.use(parameter(app))

检验使用
ctx.verifyParams({
name: {type: 'string', require: true}
})

5、koa-static 静态文件

npm install koa-static --save

const path = require('path')
const kstatic = require('koa-static')
app.use(kstatic(path.join(__dirname, 'upload')))
app.use(kstatic(path.join(__dirname, 'task')))
// http://localhost:8000/index.html => 访问:task/index.html

6、koa-body

npm install koa-body --save
npm install path

const path = require('path')
const kbody = require('koa-body')
app.use(kbody({
	multipart: true,
	formidable: {
		uploadDir: path.join(__dirname, '/uploads'), // 图片上传目录
		keepExtensions: true, // 保留扩展名
	}
}))

7、koa-jwt鉴权

[https://www.npmjs.com/package/koa-jwt]

npm install koa-jwt --save

const jwt = require('koa-jwt')
const {secret} = require('./config')
const auth = jwt({secret})

const auth = async(ctx, next) => {
	const {a = ''} = ctx.request.header;
	const token = a.replace('Bee', '');
	try{
		const user = jsonwebtoken.verify(token,secret);
		ctx.state.user = user;
	}catch(err){
		ctx.throw(401, err.message);
	}
	await next();
}

8、svg-captcha图片验证码

npm install svg-captcha

使用记录

router.get('/sc', async (ctx) => {
    let vd = sc.create({
        size: 6, // 显示的验证码展示个数
        ignoreChars: '0oli', //验证码中排除的字符
        noise: 2, // 干扰线条的数量
        color: true, // 验证码字符颜色
        background: '#cc9966', // 验证码背景色
        fontSize: 50, // 字体大小
        width: 100, // 图片宽度
        height: 40 // 图片高度
    })
    ctx.response.body = vd
})

接口返回

{text: "p2Rt", data: "<svg xmlns="http://www.w3.org/2000/svg" width="100…48 27,82 15" stroke="#5be5a0" fill="none"/></svg>"}

9、koa-better-body

https://www.npmjs.com/package/koa-better-body

npm i koa-better-body

参考文献

[https://blog.csdn.net/qq_43389371/article/details/113614934?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2defaultCTRLISTdefault-1-113614934-blog-107136469.pc_relevant_multi_platform_whitelistv1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2defaultCTRLISTdefault-1-113614934-blog-107136469.pc_relevant_multi_platform_whitelistv1&utm_relevant_index=1]

[https://blog.csdn.net/weixin_34015336/article/details/91466114]

posted on 2022-09-08 16:51  羽丫头不乖  阅读(245)  评论(0编辑  收藏  举报