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)
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM