@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
// 放行的域名、地址,使用 * 表示允许所有源地址
.allowedOrigins("*")
// 是否允许证书 不再默认开启,是否发送 Cookie
.allowCredentials(true)
// 设置允许的http请求方法 [这里也可以传入多个可变参数:"GET","POST","DELETE" ]
.allowedMethods("*")
// 跨域允许时间 预检请求的有效期
.maxAge(3600);
}
}
如上配置了跨域后,发起请求报错
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.
大概意思是:allowCredentials为true时,allowedOrigins不能包含特殊值“*”,因为不能在“Access Control Allow Origin”响应头上设置该值。要允许凭据指向一组源,请显式列出它们,或者考虑改用“allowedOriginPatterns”。
.allowedOrigins
不再可用。即如果之前springboot项目中跨域配置正常,后续如果报错,考虑将.allowedOrigins替换成.allowedOriginPatterns即可。
解决办法:
将.allowedOrigins
替换成.allowedOriginPatterns
即可。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
// 放行的域名、地址,使用 * 表示允许所有源地址
.allowedOriginPatterns("*") // 此处为 将 allowedOrigins 修改成 allowedOriginPatterns
// 是否允许证书 不再默认开启,是否发送 Cookie
.allowCredentials(true)
// 设置允许的http请求方法 [这里也可以传入多个可变参数:"GET","POST","DELETE" ]
.allowedMethods("*")
// 跨域允许时间 预检请求的有效期
.maxAge(3600);
}
}
将 .allowCredentials(true) 改成 allowCredentials(false)【不推荐】