每次请求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);
    }

}
相关推荐
工业甲酰苯胺4 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
brzhang4 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
深圳卢先生4 小时前
CentOS 安装jenkins笔记
笔记·centos·jenkins
止观止4 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms4 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登4 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
u_topian5 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
Lin Hsüeh-ch'in5 小时前
如何彻底禁用 Chrome 自动更新
前端·chrome
augenstern4166 小时前
HTML面试题
前端·html
张可6 小时前
一个KMP/CMP项目的组织结构和集成方式
android·前端·kotlin