Nest.js 实战 (七):如何生成 SVG 图形验证码

具体步骤

  1. 安装依赖
powershell 复制代码
pnpm add svg-captcha
  1. 在控制器中使用
ts 复制代码
import { Controller, Get, Res, Session } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; // swagger 接口文档
import { Response } from 'express';
import svgCaptcha from 'svg-captcha';

import { VerifyCodeResponseDto } from './dto/response-auth.dto';

@ApiTags('身份鉴权')
@Controller('auth')
export class AuthController {
  /**
   * @description: 获取图形验证码
   */
  @Get('captcha') //当请求该接口时,返回一张随机图片验证码
  @ApiOkResponse({ type: VerifyCodeResponseDto })
  @ApiOperation({ summary: '获取图形验证码' })
  async getCaptcha(@Session() session: Api.Common.SessionInfo, @Res() res: Response) {
    const captcha = svgCaptcha.createMathExpr({
      //可配置返回的图片信息
      size: 4, // 验证码长度
      ignoreChars: '0oO1ilI', // 验证码字符中排除 0oO1ilI
      noise: 2, // 干扰线条的数量
      width: 132,
      height: 40,
      fontSize: 50,
      color: true, // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有
      background: '#fff',
    });
    session.captchaCode = captcha.text; //使用session保存验证,用于登陆时验证
    res.type('image/svg+xml'); //指定返回的类型
    return res.send(captcha.data); //给页面返回一张图片
  }
}

更多详细文档:svg-captcha

Session 验证

在客户端登录的时候,我们就能根据传过来的验证码与 Session 中的信息判断是否正确:

ts 复制代码
/**
  * @description: 用户登录
  */
 async login(params: LoginParamsDto, session: Api.Common.SessionInfo) {
    // 获取验证码
   const { captchaCode } = params;
   // 判断验证码
   if (captchaCode.toUpperCase() !== session.captchaCode.toUpperCase()) {
     return responseMessage(null, '验证码错误', -1);
   }

   // 验证成功,返回 token
   return responseMessage(tokens);
 }

效果演示

相关推荐
harrain几秒前
html里引入使用svg的方法
前端·svg
咬人喵喵2 小时前
SVG 答题类互动模板汇总(共 16 种/来自 E2 编辑器)
编辑器·svg·e2 编辑器
咬人喵喵3 小时前
16 类春节核心 SVG 交互方案拆解(E2 编辑器实战)
前端·css·编辑器·交互·svg
李少兄2 天前
简单讲讲 SVG:前端开发中的矢量图形
前端·svg
咬人喵喵12 天前
文生图:AI 是怎么把文字变成画的?
人工智能·编辑器·svg
咬人喵喵12 天前
JavaScript 变量:let 和 const 该用谁?
前端·css·编辑器·交互·svg
1024肥宅14 天前
综合项目实践:可视化技术核心实现与应用优化
svg·webgl·canvas
咬人喵喵14 天前
18 类年终总结核心 SVG 交互方案拆解
前端·css·编辑器·交互·svg
咬人喵喵14 天前
告别无脑 <div>:HTML 语义化标签入门
前端·css·编辑器·html·svg
xiangxiongfly9151 个月前
CSS svg
前端·css·svg