跨域
跨域:指的是浏览器不能执行其他网站的脚本,它是由浏览器的同源策略造成的。是浏览器对JavaScript施加的安全限制
同源策略:是指协议,域名,端口都要相同,其中有一个不同都会产生跨域
都写在统一的一个配置类中,在gateway下建一个config包,CrosConfiguration,
代码示例如下:
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
或者:(取自renren-fast)即renren开源
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}

浙公网安备 33010602011771号