F12控制臺報錯:Access to XMLHttpRequest at 'XXX from origin ' http://localhost:8001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values ' http://localhost:8001, http://localhost:8001', but only one is allowed.
實際后臺請求成功了,但是還是顯示報錯然后發(fā)現(xiàn)出現(xiàn)重復headers,標頭只能一個。

解決方法
就是去除掉多次的跨域配置,只保留一次。比如我在網(wǎng)關配置了一個跨域,然后使用子項目時里面的config又配置有跨域,所以我們需要把子項目里的跨域配置注釋掉只保留的網(wǎng)關的跨域配置。或者在微服務跨域配置中增加
spring:
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials Vary, RETAIN_UNIQUE
security跨域配置:

gateway網(wǎng)關跨域配置:
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.server.WebFilter;
import org.springframework.web.util.pattern.PathPatternParser;
/**
* 跨域配置
*
* @author zc
*/
@Configuration
public class CorsConfig
{
@Bean
public WebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
//允許攜帶cookie的地址進行跨域
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new
PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
總結微服務中解決跨域問題主要分為如下情況:
情況1:針對單個服務的跨域問題,增加允許跨域配置類即可。
如,前端vue+單業(yè)務微服務
情況2:有網(wǎng)關時,網(wǎng)關配置允許跨域,微服務不配置。微服務項目網(wǎng)關服務為Gateway,則要求所有請求統(tǒng)一走網(wǎng)關,無需給每個微服務都配置跨域,只需要給網(wǎng)關微服務gateway配置跨域即可。
如,前端vue+網(wǎng)關服務gateway+業(yè)務微服務
情況3:有網(wǎng)關時,網(wǎng)關配置允許跨域,微服務配置允許跨域。需要在網(wǎng)關的配置里加上重復請求頭。配置DedupeResponseHeader=Vary Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_UNIQUE。此時走不走網(wǎng)關,都沒有跨域問題。
如,前端vue+網(wǎng)關服務gateway+業(yè)務微服務/認證授權微服務
情況4:網(wǎng)關不配置,微服務配置允許跨域。請求如果走網(wǎng)關,則會存在跨域問題。不走網(wǎng)關,直接訪問微服務,沒有跨域問題。文章來源:http://www.zghlxwxcb.cn/news/detail-479856.html
情況5:網(wǎng)關不配置,微服務不配置。走不走網(wǎng)關都會存在跨域問題。文章來源地址http://www.zghlxwxcb.cn/news/detail-479856.html
到了這里,關于gateway網(wǎng)關導致多重跨域問題The ‘Access-Control-Allow-Origin‘ header contains multiple values的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!