Nestjs (Session)

202 阅读1分钟

一、Nestjs Session简单介绍

session是另一种记录客户状态的机制,不同的是Cookie保存在客户端浏览器中,而session保存在服务器上。

二、Nestjs Session的工作流程

当浏览器访问服务器并发送第一次请求时,服务器端会创建一个session对象,生成一个类似于key,value的键值对, 然后将key(cookie)返回到浏览器(客户)端,浏览器下次再访问时,携带key(cookie),找到对应的session(value)。 客户的信息都保存在session中

不先下载插件 都属于耍流氓

yarn add express-session
yarn add @types/express-session

使用

import * as session from 'express-session'

app.use(session({
    secret:'zgy',
    name:'zgy',
    rolling:true,
    cookie:{maxAge:999999},
    resave:false,
    saveUninitialized:false
 }))

一个验证码的简单例子 ( 只针对session的一个例子 不做其他的逻辑判断 )

yarn add svg-captcha
@Get('code')
  getSvgCode(@Session() session) {
    const c = svgCaptcha.create({
      size: 4,
      fontSize: 50,
      background: '#f00',
      width: 100,
      height: 50,
    });
    // 存
    session.code = c.text.toLocaleUpperCase();
    return {
      code: 200,
      data: c.data,
      message: 'ok',
    };
  }
@Post('login')
  createUser(@Body() body,@Session() session) {
    let code = body.code.toLocaleUpperCase()
    //取
    let sessionCode = session.code
    if(code == sessionCode){
      return {
        code:200,
        data:{},
        message:'ok'
      }
    }
    return {
      code:200,
      data:{},
      message:"code不对"
    }
  }

Vue3 对接测试一下

<template>
  <input type="text" v-model="captcha" />
  <svg v-html="img" @click="changeCaptcha"></svg>
  <button @click="submit">提交</button>
</template>

<script lang="ts" setup>
import axios from "axios";
import { onMounted, ref } from "vue";

const img = ref<string>("");
const captcha = ref<string>("");
const getCode = () => {
    axios({
      url: "http://127.0.0.1:3000/demo/code",
      method: "get",
      withCredentials: true,
    }).then((res) => {
      img.value = res.data.data;
    });
};
const changeCaptcha = () => getCode();

onMounted(() => {
  getCode();
});

const submit = () => {
  axios({
    url: "http://127.0.0.1:3000/demo/login",
    method: "post",
    data: {
      code: captcha.value,
    },
    withCredentials: true,
  }).then((res) => {
    console.log(res);
  });
};
</script>

image.png

image.png

image.png

image.png