安装express-session
npm i express-session
引入 注册session
import * as session from 'express-session';import { NestFactory } from '@nestjs/core';
import {DocumentBuilder,SwaggerModule,
} from '@nestjs/swagger';import { AppModule } from './app.module';async function bootstrap() {// NestFactory 用来创建 Nest 应用实例const app = await NestFactory.create(AppModule);// secret: 生成服务端session 签名 可以理解为加盐// name: 生成客户端cookie 的名字 默认 connect.sid// cookie: 设置返回到前端 key 的属性,默认值为{ path: ‘/’, httpOnly: true, secure: false, maxAge: null }。// rolling:在每次请求时强行设置 cookie,这将重置 cookie 过期时间(默认:false)// 配置swgui接口文档const config = new DocumentBuilder().setTitle('Cats example').setDescription('The cats API description').setVersion('1.0').addTag('cats').build();const document = SwaggerModule.createDocument(app, config);SwaggerModule.setup('api', app, document);app.use(session({ secret: "XiaoMan", name: "xm.session", rolling: true, cookie: { maxAge: null } }))// restful版本控制// app.enableVersioning({// type: VersioningType.URI// })await app.listen(3000);
}
bootstrap();
安装验证码插件 svgCaptcha
npm install svg-captcha -S
验证码接代码如下
import * as svgCaptcha from 'svg-captcha';
import {Body,Controller,Get,Post,Req,Res,Session,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller('wei')
export class WeiController {constructor(private readonly weiService: WeiService) {}// 获取验证码接口@Get('code')createCode(@Req() req, @Res() res, @Session() session) {const captcha = svgCaptcha.create({size: 4,//生成几个验证码fontSize: 50, //文字大小width: 100, //宽度height: 34, //高度background: '#cc9966', //背景颜色})req.session.code = captcha.text //存储验证码记录到sessionres.type('image/svg+xml')res.send(captcha.data)}// 效验验证码@Post('create')createUser(@Body() body, @Session() session) {// console.log("@!@@", body, session.code)if (session.code === body?.code) {return {message: "验证码正确!!!!!"}} else {return {message: "验证码错误!!!!!!!!!!!!!!!"}}}
}
结果