【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);
}
解决方法:
既然我们知道了出现问题的原因,那解决办法很简单,就是去掉一层跨域设置。
去掉后,经测试可以成功下载了。