React发送Fetch请求后无法获取Spring Boot响应问题求助
问题排查与解决方案
一、React端请求代码问题
你当前的fetch调用存在两处关键问题:
Access-Control-Allow-Credentials是服务器返回的响应头,不需要在客户端请求头中设置,属于多余配置。fetch返回的data是Response对象,并非直接的响应体数据,必须调用.json()方法解析后才能获取实际内容。- 如果后端允许携带凭证(如Cookie),需在
fetch配置中添加credentials: 'include',与后端的allowCredentials配置对应。
修改后的React代码:
save(registerDTO) { fetch('http://localhost:8080/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': '*/*' }, credentials: 'include', body: JSON.stringify(registerDTO) }) .then(response => { if (!response.ok) { throw new Error('请求异常'); } return response.json(); // 解析响应体为JSON格式 }) .then(data => { console.log('响应数据:', data); // 此处可直接获取包含Token的Map const token = data.token; // 根据实际返回的字段名提取Token }) .catch(error => console.warn('请求错误:', error)) }
二、Spring Boot端CORS配置冲突问题
你同时使用了@CrossOrigin注解和全局CorsConfigurationSource Bean,两种配置可能冲突,建议统一采用一种方式:
方案1:保留全局CORS配置(推荐)
删除Controller上的@CrossOrigin注解,确保全局配置参数正确:
@Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 允许的源地址,不要添加路径后缀 configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000", "http://192.168.1.7:3000")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE")); configuration.setAllowedHeaders(Arrays.asList("*")); configuration.setAllowCredentials(true); // 如果Token放在响应头(如Authorization),需配置此行暴露自定义响应头 configuration.setExposedHeaders(Arrays.asList("Authorization")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; }
方案2:仅使用@CrossOrigin注解
删除全局CorsConfigurationSource Bean,在Controller上配置:
@CrossOrigin(origins = {"http://localhost:3000", "http://192.168.1.7:3000"}, allowCredentials = "true") @RestController @RequestMapping("/api/auth") public class AuthController { // 你的接口代码 }
三、验证步骤
- 打开Chrome开发者工具Network面板,定位
register请求:- 查看Response标签,确认是否返回预期的JSON数据。
- 查看Headers标签的Response Headers,确认存在
Access-Control-Allow-Origin(值为你的前端地址)、Access-Control-Allow-Credentials: true(若配置了凭证)。
- 查看Spring Boot日志,确认
registerService.saveUser(registerDTO)返回的Map中确实包含Token字段。
内容的提问来源于stack exchange,提问作者Robs
相关产品推荐
相关产品推荐

