Spring Global CORS配置不起作用,但控制器级配置不起作用
我试图通过WebMvcConfigurerAdapter
显示的WebMvcConfigurerAdapter
全局配置CORS。 测试我通过我创建的小节点应用程序来模拟外部服务。 当我尝试这种方法时,响应不包含正确的标题并且失败
XMLHttpRequest cannot load http://localhost:8080/api/query/1121. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:333' is therefore not allowed access.
全球配置
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/query/**") .allowedOrigins("*") .allowedHeaders("*") .allowCredentials(true); } }
但是,当我使用@CrossOrigin
注释时,它可以很好地响应正确的标题。
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*") @RestController @RequestMapping(value = "/api/query", produces = MediaType.APPLICATION_JSON_VALUE) public class QueryController { ...... }
产生
Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http://localhost:333
为了使全局配置工作,我缺少什么(按照https://spring.io/blog/2015/06/08/cors-support-in-spring-framework中的说明)。 因为注释控制器工作得很好,我觉得我错过了一些简单的东西。
为了使全局CORS配置起作用,客户端必须在OPTIONS请求中添加这两个头。
Origin: http://host.com Access-Control-Request-Method: POST
但是@CrossOrigin注释只需要“Origin”标题。
您的客户端可能会添加“Origin”标头,但缺少“Access-Control-Request-Method”…..这就是为什么它适用于@CrossOrigin,但不适用于全局配置。
你没有在它声明的方法,默认情况下只接受get方法。 尝试registry.allowedMethods("*");
在遇到此问题中记录的确切问题后,我能够使Spring Global CORS配置正常工作。 我不得不做两件事:
-
如果allowCredentials为true,则allowedOrigins不能为*。 这在Mozilla.org上有记录
-
从spring XML中删除mvc:annotation-driven。 不能同时拥有XML配置和@EnableWebMvc。 没有@EnableWebMvc,全局类将无法工作,因此必须删除mvc:annotation-driven。
我认为您的映射定义缺少*
:
registry.addMapping("/api/query/**")
如果没有额外的*
,此配置不会映射到/api/query/1121
请求路径(但它可以在/api/query/5
)。
我遇到了类似的问题。 我将WebMvcConfigurerAdapter更改为WebMvcConfigurationSupport,它开始工作。
除此之外,我还将xml配置文件中定义的RequestMappingHandlerMapping移动到java配置。
- GWT HTTP请求响应代码0,CORS正在工作
- 如何在Spring启动时在Spring Security级别启用CORS
- Google App Engine和CORS
- 使用Java Config的全局CORS配置不起作用
- IE11 CORS拒绝https上的OPTIONS
- 在Play Framework 2.4.x中解决CORS问题
- 使用Spring Framework为OPTIONS请求启用CORS
- 请求的资源上不存在Access-Control-Allow-Origin标头
- 使用application / json contentType的AJAX POST调用获取“no’Access-Control-Allow-Origin’标头”错误