使用的库svg-captcha
安装库
npm i svg-captcha@1.4.0
使用库
封装验证码中间件 ```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({
seze: 6,
ignoreChars: 'iIl1o0',
noise: 6,
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’) {
if (req.body.captcha.toLowerCase() === req.session.captcha) {
next();
} else {
req.session.captcha = '';
res.send({ content: '验证码错误' });
}
} else {
next();
}
} router.post(‘*’, validCaptcha) module.exports = router;
- `captcha = svgCaptcha.create` 创建一个普通的验证码
![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)
- 创建一个运算的二维码
![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)
```json
svgCaptcha.createMathExpr({
size: 6,
ignoreChars: 'iIl1o0',
noise: 6,
color: true
})
- size: 验证码大小
- ignoreChars: 验证码中剔除掉的字符穿
- nosie:6 用多少条干扰线
- color: 是否具有颜色
说明:
svgCaptcha.createMathExpr
会创建一个对象返回- 对象两个属性text,data
- text: 运算验证码的运算后的值
- data: svg的对象
- 这里,把验证码的计算的的值保存在
req.seession.captcha
里面,并且不区分字母的大小写 - 当下一次登录接口请求的时候(也可以自定义其他需要验证的接口),这里拦截所有的post的请求方法,
router.post('*',validCaptcha)
- 在validCaptcha验证函数里面,通过请求的接口地址和请求的类型(post)来做验证码验证
注意
- 服务端: 每次请求无论是成功还是失败,都要删除验证码
- 客户端: 无论是登录接口失败,还是验证码接口验证失败,都需要从新去请求新的验证码