【SpringBoot】has been blocked by CORS policy:The 'Access-Control-Allow-Origin' header contains multiple values 'xxx, xxx', but only one is allowed.

前端通过浏览器调后端服务RESTFul接口,报错如下图:

 现象:

响应头信息重复,如下图,但是用postman调接口响应是正常的。

原因:

是由于项目中设置了双跨域配置导致的问题。一层是网关服务中包含跨域配置,另一层是服务中设置了跨域配置。

配置如下代码:

package com.xxx.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(3600L);
        corsConfiguration.addAllowedMethod(HttpMethod.POST);
        corsConfiguration.addAllowedMethod(HttpMethod.GET);
        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
        corsConfiguration.addAllowedMethod(HttpMethod.PUT);
        corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

解决方法:

既然我们知道了出现问题的原因,那解决办法很简单,就是去掉一层跨域设置。在这里我去掉了服务中的跨域配置(保留网关的跨域设置)

 

posted @ 2021-01-21 18:12  温柔的星空,让你感动  阅读(11213)  评论(0编辑  收藏  举报