一 完整的异常提示
When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
二 配置文件
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 跨域 这前端项目设置了devServer proxy代理 故此代码也不起作用
*/
@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 是否发送cookie
config.setAllowCredentials(true);
// 允许的网站域名,全允许则设为 *
//config.addAllowedOrigin("*");
config.addAllowedOriginPattern("*");
// 允许 HEADER 或 METHOD , * 为全部
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
// 这个顺序很重要,为避免麻烦请设置在最前
bean.setOrder(0);
return bean;
}
}
解决方法:
config.addAllowedOrigin("*"); 换成config.addAllowedOriginPattern("*");