Java SpringBoot中如何配置CORS策略允许React前端跨域访问
SpringBoot + React跨域CORS永久解决方案
报错核心原因是SpringBoot后端默认未放行前端
http://localhost:3000的跨域请求,所有永久方案均在后端侧实现,无需依赖浏览器插件,常用配置方式如下:
1. 局部接口/Controller配置
- 适用于仅需要部分接口放行跨域请求的场景
- 直接在对应的Controller类或者接口方法上添加
@CrossOrigin注解即可:
// 加在Controller类上,该类下所有接口都允许来自http://localhost:3000的请求 @CrossOrigin(origins = "http://localhost:3000") @RestController public class TestController { // 也可以加在单个方法上,仅该接口放行 @PostMapping("/run") public String run() { return "success"; } }
2. 全局跨域配置(全项目生效)
- 适用于需要整个项目所有接口都放行跨域请求的场景,新增配置类实现
WebMvcConfigurer接口即可:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 匹配所有接口 .allowedOrigins("http://localhost:3000") // 允许的前端源,生产环境替换为线上前端地址 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法 .allowCredentials(true) // 允许携带身份凭证(如Cookie) .maxAge(3600); // 预检请求缓存时间,单位秒 } }
3. 集成Spring Security的额外配置
如果项目引入了Spring Security安全框架,需要在安全配置类中额外开启CORS支持,否则上述配置会被安全框架拦截:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() // 开启CORS支持,会自动读取上面的全局CORS配置 // 其他安全配置省略 .csrf().disable(); } }
注意事项
- 生产环境不要将
allowedOrigins设置为*,会允许所有来源的跨域请求,存在安全风险,需明确填写允许的前端服务地址 - 开发环境也可以通过React的
setupProxy配置前端代理转发请求,临时规避跨域问题,但生产环境仍需要后端配置跨域或者统一用网关转发请求
内容的提问来源于stack exchange,提问作者vynabhnnqwxleicntw
相关产品推荐
相关产品推荐

