这个问题困了我一下午,结果早上吃完早饭,几分钟就发现了问题, 干饭人 干饭魂…
昨天刚开始搭建项目就遇到前后端交互的跨域问题, 然后网上当然是百度一波了
嗯, 然而各种尝试 , 嗯,没用的… 后续直接放弃了,打算今天直接用最古老的写法,自行添加请求头
但是 … 但是 今天早上自己打个断点跑了下代码,发现这个东东…
public void validateAllowCredentials() {
if (this.allowCredentials == Boolean.TRUE &&
this.allowedOrigins != null && this.allowedOrigins.contains(ALL)) {
throw new IllegalArgumentException(
"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.");
}
}
这是位于 org.springframework.web.cors 包下面的一个方法 , 日志打印并没有打出来,唉
以为是日志配置问题 , 检查没啥,再看代码 发现 是这个异常被 try住了 ,如下
public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
validateMethodMapping(handlerMethod, mapping);
Set directPaths = AbstractHandlerMethodMapping.this.getDirectPaths(mapping);
for (String path : directPaths) {
this.pathLookup.add(path, mapping);
}
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
corsConfig.validateAllowCredentials();
this.corsLookup.put(handlerMethod, corsConfig);
}
this.registry.put(mapping,
new MappingRegistration<>(mapping, handlerMethod, directPaths, name, corsConfig != null));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}
结论
就是第一段代码中描述的那样 当 allowCredentials 为true 时, allowedOrigins 不能被设置成 “*” . @since 5.3
新版本才有的一个约束条件.
度娘出来好多这个地方都是 true , 下次再遇到这种问题 大家都可以但是自己的就不行,可以考虑下spring的版本问题.
对了 ,补充一点 如果你也用到 SpringSecurity 记得一定要加上 这个配置
.and().cors().and().csrf().disable();



