跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。
我们这里利用CORS策略,对我们的网关进行修改,让他接收到跨域请求的时候忽略掉OPTION中的报头不同。
这里我们创建个config包,来装跨域配置
spirngbot配置中在CorsWebFilter设置了跨域问题,我们只需要写一个方法覆盖他即可,翻看源码我们可以发现他需要两个类,一个是CorsConfigurationSource还有一个是CorsProcessor,而CorsConfigurationSource是个接口,他的实现类是UrlBasedCorsConfigurationSource,我们要配置的就是它
package com.zsp.zspmall.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class ZspMallCorsConfig {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
corsConfiguration.addAllowedHeader(""); :允许所有请求头
corsConfiguration.addAllowedMethod(""); :允许所有请求方法,例如get,post等
corsConfiguration.addAllowedOrigin("*");允许所有的请求来源
corsConfiguration.setAllowCredentials(true); 允许携带cookie
source.registerCorsConfiguration("/**",corsConfiguration); 对所有经过网关的请求都生效
看不懂也没事,直接把这个粘到你的配置类里即可。