100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > koa2 中使用 svg-captcha 生成验证码

koa2 中使用 svg-captcha 生成验证码

时间:2021-03-07 03:43:15

相关推荐

koa2 中使用 svg-captcha 生成验证码

1. 安装svg-captcha

$ npm install --save svg-captcha

2. 使用方法

生成有4个字符的图片和字符串

const svgCaptcha = require('svg-captcha')const cap = svgCaptcha.create({size: 4, // 验证码长度width:160,height:60,fontSize: 50,ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1inoise: 2, // 干扰线条的数量color: true, // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有background: '#eee' // 验证码图片背景颜色})console.log(c);// {data: '<svg.../svg>', text: 'abcd'}

如图:

生成一个算术式和计算结果

const cap = svgCaptcha.createMathExpr({size: 4, // 验证码长度width:160,height:60,fontSize: 50,ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1inoise: 2, // 干扰线条的数量color: true, // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有background: '#eee' // 验证码图片背景颜色})

如图:

3. 在 koa2 项目中使用

const Koa = require('koa'); const Router = require('koa-router') // koa 路由中间件 const svgCaptcha = require('svg-captcha')const app = new Koa();const router = new Router(); // 实例化路由 router.get('/home', async (ctx, next) => {const cap = svgCaptcha.create({size: 4, // 验证码长度width:160,height:60,fontSize: 50,ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1inoise: 2, // 干扰线条的数量color: true, // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有background: '#eee' // 验证码图片背景颜色})let img = cap.data // 验证码let text = cap.text.toLowerCase() // 验证码字符,忽略大小写ctx.type = 'html'ctx.body = `${img}<br><a href="javascript: window.location.reload();">${text}</a>`});app.use(router.routes());app.listen(3333, () => {console.log('This server is running at http://localhost:' + 3333)})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。