在我用Rails 3编写的开发服务器上,我在应用程序控制器中设置CORS标头以允许跨域访问:
class ApplicationController < ActionController::Base
before_filter :cross_domain_setup
# ...
def options_request
head :no_content
end
def cross_domain_setup
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, PUT, POST, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Content-Type, X-Requested-With"
end
# ...
end
# in routes.rb:
match "*path" => "application#options_request", constraints: { method: "OPTIONS" }
这是我的前端代码(Sencha Touch):
// note: this should probably be done using MVC, but my server doesn't
// have a RESTful API for this particular resource
var statusText = accepted ? "accepted" : "ignored";
Ext.Ajax.request({
url: "http://localhost:3000/friends/requests",
method: "PUT",
params: {
friend_request: {
_id: friendRequest.internalId,
status: statusText
}
},
success: success,
failure: failure
});
这会发送以下HTTP请求:
OPTIONS /friends/requests?_dc=1388320908671 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: PUT
Origin: http://localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Access-Control-Request-Headers: x-requested-with, content-type
Accept: */*
Referer: http://localhost/path/to/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
我的服务器响应:
HTTP/1.1 204 No Content
Date: Sun, 29 Dec 2013 12:41:48 GMT
Status: 204 No Content
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Requested-With
X-UA-Compatible: IE=Edge
Cache-Control: no-cache
Set-Cookie: blahblahblah; path=/; HttpOnly
X-Request-Id: 01157976a93af661045eefdf4b8beb2e
X-Runtime: 0.016029
这看起来都很正确。那么为什么我在Developer Tools中得到以下错误?
XMLHttpRequest cannot load http://localhost:3000/friends/requests?_dc=1388320920825. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
并非所有请求都被阻止。我还没弄清楚原因。
可能出现什么问题?
答案 0 :(得分:0)
我认为发生的事情是所请求的资源产生了500内部服务器错误(无法将符号转换为整数等等),但这显示为阻止请求可能是因为CORS头不是因500错误而发送?
无论如何,使用rack-cors gem似乎已经解决了这个问题。现在我的前端按预期收到500错误。