Spring Boot 2.2.6版本API禁用CORS后返回HTTP 500错误如何解决
解决方案
先排查后端500根因
查看Spring Boot后端控制台的异常栈信息,确认报错是CORS配置不匹配导致,还是业务接口本身的逻辑异常。你之前使用的CorsConfiguration.applyPermitDefaultValues()默认仅放开GET、HEAD、POST三种请求方法,且不支持自定义请求头、跨域凭证携带,如果你的请求不符合上述限制,就会触发异常返回500。替换为全量CORS配置
不要直接使用默认的applyPermitDefaultValues(),手动配置符合需求的CORS规则,示例如下:
@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 本地开发填前端实际地址,生产替换为正式域名 config.setAllowedOrigins(Arrays.asList("https://localhost:8087")); // 允许所有请求方法 config.setAllowedMethods(Arrays.asList("*")); // 允许所有请求头 config.setAllowedHeaders(Arrays.asList("*")); // 允许携带跨域凭证(如Cookie、Authorization头),不需要可删除 config.setAllowCredentials(true); // 预检请求缓存时间,减少预检请求次数 config.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; }
如果你的项目集成了Spring Security,在configure(HttpSecurity http)方法中添加如下配置即可:
@Override protected void configure(HttpSecurity http) throws Exception { http // 开启CORS并使用上面的自定义配置 .cors(withDefaults()) // 本地开发可关闭CSRF校验,避免非GET请求报错 .csrf().disable(); // 保留你原有其他Spring Security配置 }
- 本地开发可选代理方案(无需修改后端)
如果仅为本地开发调试,可直接用React开发服务器的代理功能绕开CORS,无需调整后端配置:
- Vite项目在
vite.config.js中添加:
import { defineConfig } from 'vite' export default defineConfig({ server: { proxy: { '/api': { target: 'http://localhost:8180', changeOrigin: true } } } })
- Create React App项目安装
http-proxy-middleware后,在src目录下新建setupProxy.js配置代理规则即可。
配置完成后前端请求直接写/api/data/firms,不需要携带后端域名端口,不会触发CORS校验。
内容的提问来源于stack exchange,提问作者Schmank
相关产品推荐
相关产品推荐

