每次请求sessionid变化【SpringBoot+Vue】

引言:花了一晚上的时间,终于把问题解决了,一开始后端做完后,用apifox所有接口测试都是可以的,但当前端跑起来后发现接收不到后端的数据。

当我写完前后端,主页面和获取当前页面信息接口后,配置了cros注解

复制代码
@CrossOrigin

我一开始使用接口文档做了后端接口测试,测试发现当访问主页面时前端能成功接受到数据,本以为皆大欢喜了,在当我接入获取当前信息接口时并测试时发现获取不到信息,我又使用apifox进行测试接口能够获取到数据,于是我使用F12进行调试。

登录:

获取当前信息:

浏览器第一次访问时会获得sessionid存在cookie中,后续访问如果有session存着,获取当前信息时会直接用,但是并没有,由上面可以知道后端重新返回了一个sessionId给前端,导致访问后端时由于sessionId不匹配,最终无法获取到登录账号的当前用户信息。

然后又经过多次调试,最终解决了这个问题,下面把方案放上来:

首先是前端,在vue的main.js中加上这个

复制代码
axios.defaults.withCredentials = true;

在后端用配置类解决跨域问题

另一方面是corsfilter,这个会先于拦截器执行,解决跨域问题

复制代码
package com.wcw.usercenter.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
    private CorsConfiguration corsConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); //允许所有请求头
        corsConfiguration.addAllowedMethod("*"); //允许所有请求方法
        corsConfiguration.setAllowCredentials(true);//是否允许证书
        corsConfiguration.addAllowedOrigin("http://localhost:5173/"); //允许所有的请求类型
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter(){
        //存储request与跨域配置信息的容器,基于url的映射
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfig());
        return new CorsFilter(source);
    }

}
相关推荐
anOnion1 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户47949283569151 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
JieE2122 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
冬奇Lab4 小时前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent
zhangxingchao4 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒5 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic7 小时前
SwiftUI 手势笔记
前端·后端
橙子家7 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518137 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州7 小时前
CSS aspect-ratio 属性完全指南
前端