我在http://eu.app.foodev.com上运行了一个Rails应用程序,并启用了rack-cors和以下配置:
config.middleware.insert_before 0, 'Rack::Cors' do
allow do
origins /.*foodev\.com:\d*/
resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options], expose: "Location"
end
end
以下是我尝试做的一般概念:
GET
/jobs/:id
个请求
303 See Other
回复,并将Location
标头设置为其他资源网址GET
标题跟随重定向到Location
其他资源数据。以下是请求/响应周期。从OPTIONS
请求开始:
OPTIONS http://foodev.com:3000/jobs/1
Accept:*/*
Access-Control-Request-Headers:accept, x-csrf-token
Access-Control-Request-Method:GET
Host:foodev.com:3000
Origin:http://eu.app.foodev.com:3000
回复:
200 OK
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:accept, x-csrf-token
Access-Control-Allow-Methods:GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin:http://eu.app.foodev.com:3000
Access-Control-Expose-Headers:Location
Access-Control-Max-Age:1728000
Content-Length:0
Content-Type:text/plain
最后是实际的GET http://foodev.com:3000/jobs/1
请求:
GET http://foodev.com:3000/jobs/1
Accept:application/vnd.foo-v2+json
Host:foodev.com:3000
Origin:http://eu.app.foodev.com:3000
和回复:
303 See Other
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin:http://eu.app.foodev.com:3000
Access-Control-Expose-Headers:Location
Access-Control-Max-Age:1728000
Content-Length:185
Content-Type:application/json
Location:http://foodev.com:3000/skill_moderations/10
由于响应是303 See Other
(这是我想要的),用户代理(js)尝试使用Location
标头跟随重定向,但是我收到以下错误:
XMLHttpRequest cannot load http://foodev.com:3000/jobs/1. The request was redirected to 'http://foodev.com:3000/skill_moderations/10', which is disallowed for cross-origin requests that require preflight.
这里的工作流程很好但是我面临的CORS问题我不明白,也不知道如何解决。有线索吗?有人在此之前遇到过这种情况吗?
感谢。
编辑:这似乎是angular / restangular(我用来发出请求)的问题。它实际上适用于以下jquery和$ http命令:
$.ajax({
url: "http://foodev.com:3000/jobs/1",
type: "GET",
crossDomain: true,
xhrFields: {
withCredentials: true
},
headers: {
'Accept': 'application/vnd.foo-v2+json'
},
success: function (response) {
console.log(response);
},
error: function (xhr, status) {
console.log('error', status);
}
});
$http.defaults.useXDomain = true;
$http.defaults.headers.common['Accept'] = 'application/vnd.foo-v2+json';
delete $http.defaults.headers.common['X-Requested-With']
$http({
method: "GET",
url: "http://foodev.com:3000/jobs/1",
withCredentials: true,
})
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
console.log(data);
});