失效代码:
javapackage com.yukuanyan.searcher_web.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
失效原因:
allowCredentials(true)被设置成了ture,说明浏览器应该在请求时携带凭证(credential),如果使用*作为通配符会导致安全问题,所以会导致通配符
allowedOrigins("*")
失效
解决方法:
将allowCredentials()设置为false
javapackage com.yukuanyan.searcher_web.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") // allowOrigins 使用通配符时需要设置为false .allowCredentials(false) .maxAge(3600); } }