使用的库svg-captcha

安装库

npm i svg-captcha@1.4.0

使用库

  1. 封装验证码中间件 ```json const express = require(‘express’); const router = express.Router(); const svgCaptcha = require(‘svg-captcha’) router.get(‘/api/captcha’, function (req, res, next) { // const captcha = svgCaptcha.create({

    const captcha = svgCaptcha.createMathExpr({

    1. seze: 6,
    2. ignoreChars: 'iIl1o0',
    3. noise: 6,
    4. color: true

    }) const { text, data } = captcha; req.session.captcha = text.toLowerCase(); res.type(‘svg’); res.status(200).send({ success: true, msg: ‘请求成功’, content: data }) }); function validCaptcha(req, res, next) { if (req.method === ‘POST’ && req.path === ‘/api/admin’) {

    1. if (req.body.captcha.toLowerCase() === req.session.captcha) {
    2. next();
    3. } else {
    4. req.session.captcha = '';
    5. res.send({ content: '验证码错误' });
    6. }

    } else {

    1. next();

    }

} router.post(‘*’, validCaptcha) module.exports = router;

  1. - `captcha = svgCaptcha.create` 创建一个普通的验证码
  2. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/22357012/1648653841574-132c1ad3-5d6a-4c8f-9514-fc4000a9e803.png#clientId=u4b635a72-6e28-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=174&id=u1bac0805&margin=%5Bobject%20Object%5D&name=image.png&originHeight=348&originWidth=462&originalType=binary&ratio=1&rotation=0&showTitle=false&size=77765&status=done&style=none&taskId=u7b375685-d6b5-4ccf-8726-d3f32b3ca2c&title=&width=231)
  3. - 创建一个运算的二维码
  4. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/22357012/1648653906525-11e64221-a244-4ab5-98d1-e91eef36cd6f.png#clientId=u4b635a72-6e28-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=182&id=rCgWb&margin=%5Bobject%20Object%5D&name=image.png&originHeight=364&originWidth=476&originalType=binary&ratio=1&rotation=0&showTitle=false&size=25395&status=done&style=none&taskId=u7bda2040-5526-4aaa-9f4b-3c114b24604&title=&width=238)
  5. ```json
  6. svgCaptcha.createMathExpr({
  7. size: 6,
  8. ignoreChars: 'iIl1o0',
  9. noise: 6,
  10. color: true
  11. })
  • size: 验证码大小
  • ignoreChars: 验证码中剔除掉的字符穿
  • nosie:6 用多少条干扰线
  • color: 是否具有颜色

说明:

  1. svgCaptcha.createMathExpr 会创建一个对象返回
  2. 对象两个属性text,data
    1. text: 运算验证码的运算后的值
    2. data: svg的对象
  3. 这里,把验证码的计算的的值保存在req.seession.captcha里面,并且不区分字母的大小写
  4. 当下一次登录接口请求的时候(也可以自定义其他需要验证的接口),这里拦截所有的post的请求方法,router.post('*',validCaptcha)
  5. 在validCaptcha验证函数里面,通过请求的接口地址和请求的类型(post)来做验证码验证

注意

  1. 服务端: 每次请求无论是成功还是失败,都要删除验证码
  2. 客户端: 无论是登录接口失败,还是验证码接口验证失败,都需要从新去请求新的验证码