Cors
跨源资源共享 (跨域资源共享)是一种基于HTTP
头的机制,该机制通过允许服务器标示除了它自己以外的其它origin(域,协议和端口),这样浏览器可以访问加载这些资源。跨源资源共享还通过一种机制来检查服务器是否会允许要发送的真实请求,该机制通过浏览器发起一个到服务器托管的跨源资源的"预检"请求。在预检中,浏览器发送的头中标示有HTTP方法和真实请求中会用到的头
一些非简单请求方法(get/head/post)都需要一个预检请求option 来确定服务器是否可以发送请求。服务器也可以通过预检请求回复一些token信息。
//解决跨域问题 Cors 资源共享 非简单请求就会先发送option打头兵 预见请求来进行服务器请求
@Configuration
public class GulimallCorsConfiguration {
//springboot 本身提供跨域CorsWebfilter 一步一步向下寻找方法 进入CorsWebFilter中发现需要参数CorsConfigurationSourc
//创建后发现是接口 所以直接实现接口 source.registerCorsConfiguration("/**",corsConfiguration);
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//设置请求头 方法 请求来源 是否允许携带cookies
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
//注册跨域配置
source.registerCorsConfiguration("/**",corsConfiguration);
/* 接口所以 new实现类
CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {
return null;
}
} */
//跨域配置信息
return new CorsWebFilter(source);
}