https://www.cnblogs.com/antLaddie/p/14751540.html
1:配置CorsFilter(全局跨域)
import org.springframework.boot.SpringBootConfiguration;import org.springframework.context.annotation.Bean;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;/** * @Author AnHui_XiaoYang
* @Email 939209948@qq.com
* @Date 2021/5/10 17:07
* @Description
*/@SpringBootConfigurationpublicclass WebGlobalConfig {
@Bean
public CorsFilter corsFilter() {
//创建CorsConfiguration对象后添加配置CorsConfiguration config =new CorsConfiguration();
//设置放行哪些原始域 config.addAllowedOrigin("*");
//放行哪些原始请求头部信息config.addAllowedHeader("*");
//暴露哪些头部信息config.addExposedHeader("*");
//放行哪些请求方式config.addAllowedMethod("GET");//getconfig.addAllowedMethod("PUT");//putconfig.addAllowedMethod("POST");//postconfig.addAllowedMethod("DELETE");//delete
//corsConfig.addAllowedMethod("*"); //放行全部请求
//是否发送Cookieconfig.setAllowCredentials(true);
//2. 添加映射路径UrlBasedCorsConfigurationSource corsConfigurationSource =new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
//返回CorsFilterreturnnew CorsFilter(corsConfigurationSource);
}
}
如果你使用的是高版本SpringBoot2.4.4则需要改动一下,否则后台报错
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) ~[spring-web-5.3.6.jar:5.3.6]
当allowCredentials为true时,alloedOrigins不能包含特殊值“*”,因为该值不能在“Access-Control-Allow-Origin”响应头部中设置。要允许凭据访问一组来源,请显式列出它们或考虑改用“AllowedOriginPatterns”。
解决:把 config.addAllowedOrigin("*"); 替换成 config.addAllowedOriginPattern("*");
2:重写WebMvcConfigurer(全局跨域)
import org.springframework.boot.SpringBootConfiguration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/** * @Author AnHui_XiaoYang
* @Email 939209948@qq.com
* @Date 2021/5/10 17:49
* @Description
*/@SpringBootConfigurationpublicclassCorsConfigimplements WebMvcConfigurer {
@Override
publicvoid addCorsMappings(CorsRegistry registry) {
//添加映射路径registry.addMapping("/**")
//是否发送Cookie.allowCredentials(true)
//设置放行哪些原始域 SpringBoot2.4.4下低版本使用.allowedOrigins("*") .allowedOriginPatterns("*")
//放行哪些请求方式.allowedMethods(newString[]{"GET", "POST", "PUT", "DELETE"})
//.allowedMethods("*") //或者放行全部
//放行哪些原始请求头部信息.allowedHeaders("*")
//暴露哪些原始请求头部信息.exposedHeaders("*");
}
}