Nestjs实现验证码小案例

538 阅读1分钟

Nestjs获取验证码

后端

安装session包

//安装express的session包
yarn add express-session
//安装Ts的代码提示
yarn add @types/express-session

定义session

  1. 在mian.ts中将session作为中间间传入

     app.use(session())
    
  2. session里面是传一个配置项

    app.use(session({
    secret:"梦宇",
        rolling:true,
        name:"My.sid"
    }))
    

完整代码

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
//导入包
import * as session from "express-session";
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
    //传入配置
  app.use(session({secret:"梦宇",rolling:true,name:"My.sid"}))
  await app.listen(3000);
}
bootstrap();

安装验证码包

//安装包
yarn add svg-captcha
//安装ts代码提示
yarn add @types/@svg-captcha

定义验证码

 const captcha = svgCaptcha.create({
      size: 1//验证码长度
      fontSize: 50,
      width: 100,
      height: 34,
      background: "#cc9966" //背景颜色
    })
 // 传回前端
 res.type('image/svg+xml'// 将验证码返回给前端一个图片
  res.send(captcha.data) //数据部分是data

完整代码


  @Get()
  getHello(@Res() res, @Session() session) {
  const captcha = svgCaptcha.create({
      size: 1,
      fontSize: 50,
      width100,
      height34,
      background"#cc9966"
    })
  //定义session的标识值
    session.code = app.text
    res.type('image/svg+xml'),
      res.send(captcha.data)
  }

验证验证码

@Post()
createUser(@Body() body, @Session() session) {
   // 前端传回来的验证码,转换成小写
    const aeg = body.age.toLowerCase()
    //get方式获取的验证码定义的
    const code = String(session.code).toLowerCase()
    if (aeg === code) {
      return {
        code: 200,
        msg: "验证码正确",
        data: {}
      }
    } else {
      return {
        code: 200,
        msg: "验证码错误",
        data: { }
      }
    }

前端

<template>
  <input type="text" v-model="codema">
  <img :src="codeurl" alt="" @click="img">
  <button @click="submitForm"></button>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref } from "vue";
      //定义的axios
  import service from "./api";
      //验证码内容
  const codema=ref('')
  //初始的验证码图片
  const codeurl = ref("/api");
  //提交验证码数据
  const submitForm = (ever: any) => {
    service.post("", codema).then((res) => {
        img()
      });
  };
      //刷新验证码
  const img = () => {
    codeurl.value = codeurl.value + "?" + Math.random();
    console.log(97*86);
    
  };
  </script>