跨域

跨域:指的是浏览器不能执行其他网站的脚本,它是由浏览器的同源策略造成的。是浏览器对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);
}
}
posted @ 2024-05-08 18:24  暧昧d  阅读(22)  评论(0)    收藏  举报