You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot与React跨域交互时HttpSession丢失问题咨询

问题解决:React调用Spring Boot API时保持HttpSession有效

你遇到的核心问题是跨域请求中会话Cookie未正确传递,导致Spring Boot无法识别用户会话。以下是针对性修复步骤:

1. 修复React端请求配置

你的Current函数中的fetch请求未携带会话凭证,这是会话丢失的直接原因。所有需要保持会话的请求都必须添加credentials: 'include',同时还要修复response.json的调用错误:

const Current = async () =>{
  fetch('http://127.0.0.1:8080/api/v1/user/current', {
    method: 'GET',
    credentials: 'include', // 携带会话Cookie
    headers: {
        'Accept': 'application/json',
    }})
  .then(response => response.json()) // 修复:调用json()方法
  .then(response => console.log(JSON.stringify(response)))
  .catch(error => console.log(error));
}

2. 完善Spring Boot全局CORS配置

你之前的CorsConfig未开启允许携带凭证,导致浏览器拒绝传递Cookie。修改配置如下:

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:3000");
        config.setAllowCredentials(true); // 关键:允许携带凭证
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

注:你在UserController上添加的@CrossOrigin注解与全局配置可能冲突,建议保留其中一种即可(推荐全局配置)。

3. 验证Redis会话存储

你的配置使用Redis存储会话,需确保:

  • Redis服务在localhost:6379正常运行
  • 项目已引入Redis相关依赖(若未添加,需在pom.xml中补充):
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

若Redis未正常运行,Spring Boot会 fallback 到内存会话,可能导致会话异常。

4. 额外代码修复(非核心但重要)

你的showAll接口逻辑与注释矛盾,当前代码会拒绝管理员访问,需修改为:

if (!sessionUser.getRoleId().equals(ADMIN_ROLE)) {
    throw new IllegalArgumentException(UNAUTHORIZED);
}

原理说明

跨域场景下,浏览器默认不会携带Cookie,需同时满足三个条件才能正常传递:

  1. 前端请求添加credentials: 'include'
  2. 后端CORS配置开启allowCredentials = true,且allowedOrigin必须指定具体域名(不能用*)
  3. 后端会话Cookie的SameSite属性为Lax或None(Spring Boot默认是Lax,跨域场景下足够)

内容的提问来源于stack exchange,提问作者HC2102

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:54:59