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

}
相关推荐
zhangxingchao24 分钟前
Flutter中的页面跳转
前端
前端风云志1 小时前
TypeScript实用类型之Omit
javascript
烛阴1 小时前
Puppeteer入门指南:掌控浏览器,开启自动化新时代
前端·javascript
全宝2 小时前
🖲️一行代码实现鼠标换肤
前端·css·html
小小小小宇2 小时前
前端模拟一个setTimeout
前端
萌萌哒草头将军2 小时前
🚀🚀🚀 不要只知道 Vite 了,可以看看 Farm ,Rust 编写的快速且一致的打包工具
前端·vue.js·react.js
芝士加3 小时前
Playwright vs MidScene:自动化工具“双雄”谁更适合你?
前端·javascript
Carlos_sam4 小时前
OpenLayers:封装一个自定义罗盘控件
前端·javascript
前端南玖4 小时前
深入Vue3响应式:手写实现reactive与ref
前端·javascript·vue.js
wordbaby5 小时前
React Router 双重加载器机制:服务端 loader 与客户端 clientLoader 完整解析
前端·react.js