SpringBoot+ReactJS项目遇CORS跨域错误无法获取MongoDB数据如何解决?
问题根因排查&解决方案
先排除你之前尝试方法的误区
- 前端执行
npm install cors完全无效:该包是给Node.js后端服务使用的,前端项目安装不会产生任何效果,可以直接卸载。 - 仅给Controller加
@CrossOrigin注解失效大概率是因为:项目存在全局拦截器/ Spring Security配置,拦截了OPTIONS预检请求,导致跨域响应头没有被正确返回。 - Chrome跨域扩展失效一般是权限配置不到位,优先通过后端正规配置解决,不建议依赖扩展。
分步解决步骤
步骤1:先确认接口本身可正常访问
先拿Postman/ApiFox直接调用http://localhost:8080/api/auth/file,确认接口能正常返回数据、没有抛出数据库相关异常。如果接口本身调用报错,Spring异常响应默认不会携带跨域头,也会触发前端CORS报错,先把接口本身的问题修复。
步骤2:补全CORS配置(二选一即可,优先选全局配置)
方案A:补全Controller层CrossOrigin参数
把你Controller上的@CrossOrigin注解替换成如下内容:
@CrossOrigin(origins = "http://localhost:8081", allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS})
方案B:新增全局CORS配置类(更推荐,一次配置所有接口生效)
在项目里新增如下配置类即可:
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:8081") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
步骤3:如果项目集成了Spring Security,额外加放行配置
在你的Spring Security配置类中,新增跨域支持和OPTIONS请求放行规则:
@Override protected void configure(HttpSecurity http) throws Exception { http .cors() // 开启CORS支持 .and() .csrf().disable() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有预检请求 // 其余你原有配置保持不变即可 ; }
步骤4:前端请求适配(如果有鉴权场景)
如果你的接口需要携带Cookie/鉴权头,需要给axios请求加上withCredentials: true参数:
await axios .get("http://localhost:8080/api/auth/file", { withCredentials: true }) .then((res) => { console.log(res); this.setState({ folders: res.data, }); }) .catch(function (error) { console.log(error); });
内容的提问来源于stack exchange,提问作者Jeema Riyana
相关产品推荐
相关产品推荐

