1.跨域问题介绍
基于浏览器的同源策略,会对请求进行跨域判断。当协议、域名(或主机ip)、端口号不一致时,则被判断为跨域请求。此时会导致:
(1)请求从http://localhost:8081 到 http://localhost:8082 由于端口不同,是跨域。
(2)请求从https://localhost:8081 到 http://localhost:8081 由于协议不同,是跨域。
(3)请求从http://localhost:8081 到 http://www.bing.com:8081 由于ip不同,是跨域。
2.解决方案
服务端在响应时在响应头添加 Access-Control-Allow-Origin:*,告知浏览器容许跨域请求。
具体如下:
SpringBoot工程下创建允许跨域的过滤器
@Configuration
public class GlobalCorsConfig {
/**
* 允许跨域调用的过滤器
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
//允许域名进行跨域调用(设置http://localhost:8080/ 表示指定请求源允许跨域)
config.addAllowedOrigin("*");
//允许跨越发送cookie
config.setAllowCredentials(true);
//放行全部原始头信息
config.addAllowedHeader("*");
//允许所有请求方法跨域调用
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}