Access-Control-Allow-Origin header contains multiple values ‘http://xx, *‘, but only one is allowed

【SpringBoot】 Access to XMLHttpRequest at 'http://xx' from origin 'http://xx' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://xx, *', but only one is allowed.

 有两个响应头

 

原因:

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

全局配置代码如下

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径,拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

当前接口代码配置如下,(注释的代码去掉即可解决跨域问题)

    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        /**
         * 原因:全局已配置过一次了
         * 是由于项目中设置了双跨域配置导致的问题。一层是网关服务中包含跨域配置,另一层是服务中设置了跨域配置。
         */
        //response.addHeader("Access-Control-Allow-Origin", "*");  //开启后会报跨域错误
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

解决方法:

既然我们知道了出现问题的原因,那解决办法很简单,就是去掉一层跨域设置。

去掉后,经测试可以成功下载了。

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值