【发布时间】:2016-05-04 06:26:28
【问题描述】:
我在 Spring Boot 中遇到了 CORS 问题。我已经像这样配置了 CORS
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
我想这会启用所有标题和其他内容。
它非常适合 GET 请求
$.get("someUrl, function(data, status){
console.log(data[0].latitude);
});
但是每当我发出这样的 POST 请求时
$.ajax({
url: 'someUrl',
type: 'post',
dataType: 'json',
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
data: object
});
我得到以下信息
OPTIONS XHR "someUrl" [HTTP/1.1 403 Forbidden 4ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "someUrl".
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
我该如何解决这个问题?
【问题讨论】:
-
无论是什么导致了问题,我认为它不在您在问题中发布的 sn-ps 范围内。我刚刚在一个新的 Spring Boot (1.3.2.) 设置上尝试了它,代码量最少,并且当我从其他域
POST时正确添加了 CORS 标头。您使用的是哪个版本的 Boot,您的请求来自哪个用户代理POST?您的项目中的其他依赖项是否会覆盖您的 Cors 设置(或者可能是控制器上更明确的配置?)? -
我使用 Spring Boot 1.3.0.RELEASE 并且用户代理是 Firefox。实际上,它是重定向到其他 Spring Boot 应用程序的其他端点的 Api-gateway 应用程序。我使用的是 netflix 的 Zuul。
标签: spring-boot cors