nodejs使用 svg-captcha 做验证码及验证

Posted on 2022-03-08 16:57  书中枫叶  阅读(1070)  评论(0编辑  收藏  举报

一、需求

使用 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

Copyright © 2024 书中枫叶
Powered by .NET 8.0 on Kubernetes