gateway跨域问题解决方法

2022-07-04 09:36:25

在解决之前在gateway中用了全局配置类跨域

package com.sky.wlmall.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;import org.springframework.web.util.pattern.PathPatternParser;@ConfigurationpublicclassCorsConfig{@Beanpublic CorsWebFiltercorsFilter(){
        CorsConfiguration config=newCorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source=newUrlBasedCorsConfigurationSource(newPathPatternParser());
        source.registerCorsConfiguration("/**", config);returnnewCorsWebFilter(source);}}

之后却报错了:
报错提示:Access to XMLHttpRequest at ‘http://localhost:88/api/sys/menu/nav?t=1646366047125’ from origin ‘http://localhost:8001’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute

将上面的配置类修改为如下,并配置yaml就解决了:

package com.sky.wlmall.gateway.config;import org.springframework.boot.SpringBootConfiguration;import org.springframework.web.reactive.config.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@SpringBootConfigurationpublicclassCorsConfigimplementsWebMvcConfigurer{publicvoidaddCorsMappings(CorsRegistry corsRegistry){/**
         * 所有请求都允许跨域,使用这种配置就不需要
         * 在interceptor中配置header了
         */
        corsRegistry.addMapping("/**").allowCredentials(true).allowedOrigins("http://localhost:8001").allowedMethods("POST","GET","PUT","OPTIONS","DELETE").allowedHeaders("*").maxAge(3600);}}
spring:cloud:gateway:globalcors:add-to-simple-url-handler-mapping:truecors-configurations:
          '[/**]':allowedOrigins:-"http://localhost:8001"allowedMethods:-"GET"-"POST"-"DELETE"-"PUT"-"OPTIONS"allowedHeaders:"*"allowCredentials:truemaxAge:360000
  • 作者:sky~
  • 原文链接:https://blog.csdn.net/Badman0726/article/details/123273687
    更新时间:2022-07-04 09:36:25