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

效果演示

相关推荐
FungLeo2 天前
成为全栈·Node 后端篇·框架选型:Express、Koa、Fastify、NestJS 的差异与为何选 Hono
express·koa·nest.js·fastify·hono
Highcharts.js3 天前
Highcharts 渲染方式解析:SVG 默认渲染与 Boost 模块的 WebGL 加速,以及它与其他可视化库的不同
svg·webgl·可视化·canvas·highcharts·渲染方式
Highcharts.js4 天前
Highcharts 双 Y 轴分组错位柱状图・代码详解
svg·可视化·demo·highcharts·双y轴·数据示例
用户2986985301413 天前
C# 实现 PowerPoint 多格式转换:图片、PDF 与 SVG 实战
c#·.net·svg
weixin_4316004418 天前
NestJS 入门(10):日志——为什么常用 Winston?
后端·学习·日志·nest.js·winston
weixin_4316004418 天前
NestJS 入门(9):连上数据库,SQL 写在哪?
数据库·后端·sql·学习·nest.js
weixin_4316004419 天前
NestJS 入门(7):生命周期钩子——构造函数和 `OnModuleInit` 差在哪?
前端·后端·学习·node.js·nest.js
mCell19 天前
AI 时代 SVG 画图的潜力
前端·agent·svg
weixin_4316004422 天前
NestJS 入门(3):Guard 如何挡住未登录请求?
前端·后端·学习·nest.js
weixin_4316004423 天前
前端对接 SSE 的两种常见方式
前端·后端·学习·ai·sse·nest.js