Node.js第十二篇:图片随机验证码

1. 为什么需要随机验证码

防止机器恶意注册. 验证码的作用:有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上是用验证码是现在很多网站通行的方式,利用比较简易的方式实现了这个功能。虽然登陆麻烦一点,但是对社区还来说这个功能还是很有必要,也很重要。

2. Node.js实现随机验证码

安装第三方包

npm install svg-captcha --save

文档:https://www.npmjs.com/package/svg-captcha

代码演示

后端程序

const koa = require('koa')
const router = require('koa-router')()
// 导入koa-session模块
const session = require('koa-session')
// 导入svgCaptcha
const svgCaptcha = require('svg-captcha');

const app = new koa()

// 配置session
app.keys = ['some secret hurr'];
const CONFIG = {
  key: 'koa:sess', //cookie key (default is koa:sess) 
  maxAge: 86400000, // cookie 的过期时间 maxAge in ms (default is 1 days) 
  overwrite: true, //是否可以 overwrite (默认 default true) 
  httpOnly: true, //cookie 是否只有服务器端可以访问 httpOnly or not (default true) 
  signed: true, //签名默认 true 
  rolling: false, //在每次请求时强行设置 cookie,这将重置 cookie 过期时间(默认:false) 
  renew: false, //(boolean) renew session when session is nearly expired, 
};
app.use(session(CONFIG, app));

// 验证码请求路径
router.get('/imgcode', async (ctx) => {
  const captcha = svgCaptcha.create(
    {
      size: 6,   // 验证码字符数
      fontSize: 20, // 文字大小
       100,   // 图片宽度
      height: 40,   // 图片高度
      noise:5,      // 遮挡线数
      background: "#cc9966"  // 背景色
    });
  ctx.session.code = captcha.text;   // 将随机字符存入session中
  ctx.response.type = 'image/svg+xml';  // 设置响应的类型
  ctx.body = captcha.data;  
})

// 注册路由
app.use(router.routes())
// 作用: 这是官方文档的推荐用法,我们可以 看到 router.allowedMethods()用在了路由匹配 router.routes()之后,所以在当所有 路由中间件最后调用.此时根据 ctx.status 设置 response 响应头
app.use(router.allowedMethods());

app.listen(80)

前端程序

  <img id="imgcode" style=" 300px;cursor: pointer;" src="http://localhost/imgcode" alt="">
  <script>
    imgcode.onclick = function(){
      imgcode.src = 'http://localhost/imgcode?random' + Date.now()
    }
  </script>
原文地址:https://www.cnblogs.com/lpl666/p/12880609.html