Gateway网关解决跨域问题

时间:2025-03-18 08:29:54

Gateway网关解决跨域问题


跨域解释:

  • 当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域,如果两个URL的协议、域名和端口相同,则表示它们同源。

理解:浏览器会先发出一次options请求,该请求不会带任何参数(包括设置的头部,cookie等), 等待服务器端返回200, 才会发出正常的请求

环境:springcloud+gateway+axios+vue

解决方法:在网关服务中加上上面类

@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true); // 允许cookies跨域
        config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
        config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
        config.addAllowedMethod("*");// 允许提交请求的方法类型,*表示全部允许
        config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了

        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source =
                new org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}