之前找的跨域配置有时生效,有时无效,这次做了测试顺便记录一遍(nginx,Cors)跨域配置
1. springboot跨域配置
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*"); // 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); //允许的请求方法,PSOT、GET、OPTIONS等
corsConfiguration.setAllowCredentials(Boolean.TRUE);
// 2.4以后这样设置 替换 addAllowedOrigin("*)
corsConfiguration.addAllowedOrigin("*");
// corsConfiguration.setAllowedOriginPatterns(Arrays.asList(CorsConfiguration.ALL));
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
3. 注解方式
在方法或类名前面加上:@CrossOrigin
2:nginx跨域配置
location段内增加一下代码
location /api-v2/{
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*'; #设置访问源请求头
add_header 'Access-Control-Allow-Methods' '*'; #允许的请求方法
# OPTIONS 直接返回204
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://192.168.1.100:8086/;
}
以上配置取一种就好,否则会报错
has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header contains multiple values ’ *', but only one is allowed