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

1. 安装svg-captcha

$ npm install --save svg-captcha

2. 使用方法

  1. 生成有4个字符的图片和字符串
const svgCaptcha = require('svg-captcha')

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

console.log(c);
// {data: '<svg.../svg>', text: 'abcd'}

如图:

image

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

如图:

image

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', // 验证码字符中排除 0o1i
    noise: 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)
})
posted @   Mr.曹  阅读(3682)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示