You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React调用Spring Boot接口遇CORS问题:JWT令牌无法获取

Hey,我刚看到你的问题,正好之前也碰到过类似的跨域+JWT的坑,给你梳理几个最可能的原因和解决步骤:

解决React跨域调用Spring Boot JWT认证接口拿不到令牌的问题

1. 先排查React的请求代码是否正确

你在Spring的index.html里用jQuery Ajax能正常拿到token,但React的请求配置可能和jQuery有差异,这是最常见的问题:

如果你用fetch

默认不会自动解析JSON响应,也需要手动设置请求头,比如:

fetch('http://localhost:8080/auth', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=utf-8' // 必须和后端要求一致
  },
  body: JSON.stringify(loginData)
})
.then(response => {
  if (!response.ok) throw new Error('请求异常');
  return response.json(); // 关键:把响应体转成JSON对象
})
.then(data => {
  console.log(data.token); // 这里应该就能拿到令牌了
})
.catch(err => console.error(err));

如果你用axios

axios默认会处理JSON,但要注意响应数据在response.data里,比如:

axios.post('http://localhost:8080/auth', loginData, {
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})
.then(response => {
  console.log(response.data.token); // 别直接拿response,要取data属性
})
.catch(err => console.error(err));

2. 检查Spring Boot的CORS配置是否完整

React是跨域请求(3000端口→8080端口),而Spring的index.html是同域请求,所以必须确保后端CORS配置覆盖跨域场景:

全局CORS配置示例:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000") // 明确允许React的源,生产环境别用*
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true); // 如果需要携带Cookie或认证信息就开启
    }
}

搭配Spring Security的注意点:

如果你的项目用了Spring Security,必须让CORS在Security过滤器之前生效:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors(Customizer.withDefaults()) // 先启用CORS
            .csrf(csrf -> csrf.disable()) // 开发环境可以先禁用CSRF,POST请求需要
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/auth").permitAll() // 确保/auth接口无需认证
                .anyRequest().authenticated()
            );
        return http.build();
    }
}

3. 用浏览器开发者工具排查细节

打开F12开发者工具,重点看两个地方:

  • 控制台:有没有CORS相关的错误提示?比如Access-Control-Allow-Origin缺失之类的
  • 网络标签:找到/auth请求,查看响应体是否真的返回了token。如果响应体有token但React拿不到,就是代码解析问题;如果响应体没有,就要检查后端接口逻辑

4. 确认后端接口逻辑对跨域请求一致

你可以用Postman直接调用http://localhost:8080/auth,看是否能拿到token:

  • 如果Postman能拿到,说明后端逻辑没问题,问题在React请求或CORS配置
  • 如果Postman也拿不到,那就要检查后端/auth接口的代码,是否存在只给同域请求返回token的逻辑

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

火山引擎 最新活动