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);
 }

效果演示

相关推荐
xiaoxue..13 天前
Nest.js 框架 企业级开发通关手册
面试·typescript·node.js·开发框架·nest.js
谜亚星22 天前
SVG学习(五)
前端·svg
harrain23 天前
前端svg精微操作局部动态改变呈现工程网架状态程度可视播放效果
前端·svg·工程网架图
我真的叫奥运24 天前
scss mixin svg 颜色控制 以及与 png 方案对比讨论
前端·svg
harrain24 天前
html里引入使用svg的方法
前端·svg
咬人喵喵24 天前
SVG 答题类互动模板汇总(共 16 种/来自 E2 编辑器)
编辑器·svg·e2 编辑器
咬人喵喵25 天前
16 类春节核心 SVG 交互方案拆解(E2 编辑器实战)
前端·css·编辑器·交互·svg
李少兄1 个月前
简单讲讲 SVG:前端开发中的矢量图形
前端·svg
咬人喵喵1 个月前
文生图:AI 是怎么把文字变成画的?
人工智能·编辑器·svg
咬人喵喵1 个月前
JavaScript 变量:let 和 const 该用谁?
前端·css·编辑器·交互·svg