nodejs使用 svg-captcha 做驗證碼及驗證


一、需求

使用 nodejs 做后端開發,需要請求驗證碼,在 github 上看到了 svg-captcha 這個庫,發現他是將 text 轉 svg 進行返回的,安全性也有保證,不會被識別成文字。

二、基本使用

安裝:

yarn add svg-captcha

1) 創建普通驗證碼:

const svgCaptcha = require('svg-captcha');

const cap = svgCaptcha.create();
console.log(cap);
// {data: '<svg.../svg>', text: 'abcd'}

調用 create() 之后,會返回一個對象,結構如下:{data:'',text:''}

  • data:驗證碼 svg 圖片
  • text: 驗證碼字符

create()的參數如下:

  • size: 4 // 驗證碼長度
  • ignoreChars: '0o1i' // 驗證碼字符中排除 0o1i
  • noise: 1 // 干擾線條的數量
  • color: true // 驗證碼的字符是否有顏色,默認沒有,如果設定了背景,則默認有
  • background: '#cc9966' // 驗證碼圖片背景顏色

示例:

2) 創建算數式驗證碼

const cap = svgCaptcha.createMathExpr(options)

示例:

 

 

三、在 express 中使用

在網頁中使用驗證碼的時候,無非是請求一個 URL ,返回一個驗證碼圖片。

1) express 中構建一個 /captcha 的路由:


const express = require('express');
const captcha = require('svg-captcha');
const router = express.Router();

router.get('/',(req,res)=>{
  const cap = captcha.createMathExpr();
  req.session.captcha = cap.text; // session 存儲
  res.type('svg'); // 響應的類型
  res.send(cap.data);
});

2) 前端使用

  <img 
    src="/captcha"
    onclick={$(event.target).attr('src','/captcha?'+Math.random())}>

 

 

 


來源:http://zhouyi.run


免責聲明!

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



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