1、什么是跨域问题:简单来说就是 协议、IP地址(域名)、端口三者其中一个不同
控制台报错:xxx has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the request resouce.
便是出现跨域问题
2、解决方案:
1、使用nginx同源策略
2、网关统一配置跨域
在配置类中添加以下配置:
@Bean //跨域配置过滤器
public CorsWebFilter corsWebFilter(){
//基于url的跨域配置
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//跨域配置
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 配置跨域
corsConfiguration.addAllowedHeader("*"); //允许那些请求头可以跨域
corsConfiguration.addAllowedMethod("*"); //允许那些请求方法可以跨域
corsConfiguration.addAllowedOrigin("/**"); //允许那些请求来源(ip/域名)可以跨域
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.setAllowCredentials(true); // 是否携带cookie
source.registerCorsConfiguration("/**",corsConfiguration); //1、那些请求路径可以跨域 2、跨域配置对象
return new CorsWebFilter(source);
}
除了在配置类中添加上述代码,当然也可以在controller类上添加上@CrossOrigin注解