浏览器请求接口,报has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 跨域问题

alwaysmove / 2024-10-12 / 原文

CORS(Cross-Origin Resource Sharing,跨源资源共享)策略阻止了一个跨域请求。

这个错误表明你的前端应用尝试从与其自身不同的域、协议或端口获取资源,而该域的响应头部没有包含Access-Control-Allow-Origin指令来明确允许这种跨域请求。

解决方法:

  记住按springboot的版本来配置,高于2.4版本,用第二种方式,用第一种方式,会不生效

  1. 在Spring Boot应用中,你可以通过添加一个WebMvcConfigurer实现来配置CORS。

    import org.springframework.context.annotation.Bean;
    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 {
     
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**") // 允许跨域的路径
                            .allowedOrigins("*") // 允许跨域请求的域名
                            .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
                            .allowedHeaders("*") // 允许的请求头
                            .allowCredentials(true); // 是否允许证书(cookies)
                }
            };
        }
    }
    1. 如果你使用的是Spring Boot 2.4.0或更高版本,可以使用新的CORS配置方式:

      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.servlet.config.annotation.CorsRegistry;
       
      @Configuration
      public class CorsConfig {
       
          @Bean
          public CorsFilter corsFilter() {
              UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
              CorsConfiguration config = new CorsConfiguration();
              config.setAllowCredentials(true);
              config.addAllowedOrigin("*");
              config.addAllowedHeader("*");
              config.addAllowedMethod("*");
              source.registerCorsConfiguration("/**", config);
              return new CorsFilter(source);
          }
      }