Session 会话
HTTP sessions provide a way to store information about the user across multiple requests, which is particularly useful for MVC applications.
HTTP 会话提供了一种跨多个请求存储有关用户的信息的方法,这对于 MVC 应用特别有用。
默认与express一起使用
安装依赖及其类型声明
pnpm i express-session
pnpm i -D @types/express-session
将express-session应用为全局中间件
// main.ts
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: 'my-secret',
resave: false,
saveUninitialized: false,
}),
);
await app.listen(3000);
}
bootstrap();
各个参数的含义
| 参数 | 解释 |
|---|---|
| secret | 生成服务端session 签名 可以理解为加盐 |
| name | 生成客户端cookie 的名字 默认 connect.sid |
| cookie | 设置返回到前端 key 的属性,默认值为{ path: ‘/’, httpOnly: true, secure: false, maxAge: null }。 |
| rolling | 在每次请求时强行设置 cookie,这将重置 cookie 过期时间(默认:false) |
(expressjs/session: Simple session middleware for Express (github.com))
实践: 实现一个验证码 前后端
后端
后端生成验证码的包
pnpm install svg-captcha -S
写一个控制器
@Get('captcha')
createCaptcha(@Session() session, @Res() res) {
const { text, data } = svgCaptcha.create({
size: 4,
fontSize: 50,
width: 100,
height: 40,
background: '#f0f0f0',
});
session.code = text;
res.type('image/svg+xml');
res.send(data);
}
并实现验证码验证
@Post('create')
createUser(@Session() session, @Body() body) {
console.log(session.code, body);
if (session.code.toLocaleLowerCase() === body?.code?.toLocaleLowerCase()) {
return {
message: '验证码正确',
};
} else {
return {
message: '验证码错误',
};
}
}
前端
使用我自己写的cli生成一个项目
pnpm dlx rika-cli c front-end-demo
配置反向代理解决跨域
// vite.config.ts
proxy:{
'/api':{
target:'http://localhost:3000/',
changeOrigin:true,
rewrite: path => path.replace(/^\/api/, ''),
}
}
页面结构
<script setup lang="ts">
/**
* @Author Rika
* @Description
* @CreateData 2024/08/25
*/
const imgUrl = ref(`/api/user/captcha?t=${new Date().getTime()}`)
function refreshImgUrl() {
imgUrl.value = `/api/user/captcha?t=${new Date().getTime()}`
}
const captcha = ref('')
function submit() {
fetch(`/api/user/create`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: captcha.value,
}),
}).then(res => res.json()).then((data) => {
console.log(data)
})
}
</script>
<template>
<img :src="imgUrl" alt="" @click="refreshImgUrl">
<input v-model="captcha" type="text">
<button @click="submit">
提交
</button>
</template>
经过测试,没有啥问题 也更理解了cookie的原理