Vue + node简单实现验证码

web实现验证码思路

(个人简单示例操作,流程可能并不规范,仅提供演示,请勿抬杠)

验证码代码流程

  1. 前端发送get请求来获取验证码图片。
    后端收到前端的生成验证码请求,生成验证码图片和验证码内容。然后将随机生成uuid值作为键,验证码内容作为值,形成一对键值对,存储在Redis中(这里存入对象)。同时根据需求设置验证码的有效期,之后把uuid的值作为cookie传回前端;
const svgCaptcha = require('svg-captcha');
const { v4: uuidv4 } = require('uuid');
const globals = require('./globals');
// 获取图形验证码
exports.getImageCode = function (req, res) {
    const captcha = svgCaptcha.create({
        inverse: false, // 翻转颜色
        fontSize: 48, // 字体大小
        noise: 2, // 干扰线条数
        width: req.query.width || 115, // 宽度
        height: req.query.height || 40, // 高度
        size: 4, // 验证码长度
        ignoreChars: '0o1i', // 验证码字符中排除 0o1i
        color: true, // 验证码是否有彩色
        background: '#cc9966', // 验证码图片背景颜色
    })
    let uuid = uuidv4();
    globals.set(uuid, captcha.text.toLowerCase());
    //保存到cookie,忽略大小写
    res.cookie('uuid', uuid)
    res.type('svg')
    res.send(captcha.data)
}
// globals.js
// 存储uuid和验证码
const codeArr = {}
// const tokenArr=[] 不考虑好了
// 获取验证码是否存在
exports.get = function (uuid) {
  return codeArr.hasOwnProperty(uuid) ? codeArr[uuid] : false;
};

// 存储验证码并设置有效期
exports.set = function (uuid, code, lifespan = 30) {
  codeArr[uuid] = code;
  // 有效期30s
  setTimeout(() => {
    Reflect.deleteProperty(codeArr, uuid);
  }, lifespan * 1000)
  return true;
};
  1. 前端获取到验证码,等待用户输入验证码之后进行提交请求。

  2. 后端同cookie拿到uuid以及用户输入的验证码内容。根据uuid取出Redis中保存的值,如果值为空,那么说明验证码已经过期;如果值不为空,取出值和前端传过来的用户输入的验证码内容进行比较,如果相等,那么就验证码输入正确,否则验证码输入错误,将结果返回给前端。

  3. 前端收到后的响应,如果验证码正确,则显示提交成功,否则重新请求后端生成验证码,然后重复上述步骤。

posted @ 2023-03-20 11:55  槑孒  阅读(49)  评论(0编辑  收藏  举报