我想设置简单的跨源资源共享使用jQuery(1.7.1)在客户端和apache服务的python(Django)服务器上启动ajax。根据所有的指示,我看了我的头设置正确,但我不断收到以下错误:CORS访问控制 - 允许来源尽管正确的标题
XMLHttpRequest cannot load http://myexternaldomain.com/get_data . Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
是我想(我不知道它甚至让过去的浏览器)的标头中发送是:
Request URL:http://myexternaldomain.com/get_data
Accept:application/json, text/javascript, */*; q=0.01
Origin:http://localhost:8080
Referer:http://localhost:8080/static/js/test-zetta.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11
的JavaScript代码是
var request = $.ajax({
url : "http://myexternaldomain.com/get_data",
type : "POST",
dataType : "json",
crossDomain : true
});
注意origin
设置正确。服务器使用下面的Python代码
def process_response(self, response):
if response.has_header('Access-Control-Allow-Origin'):
return response
response['Access-Control-Allow-Origin'] = '*'
return response
def get_orders(request):
""" Tell worker what to do """
response_data = {}
response_data['action'] = 'probe'
response = process_response(HttpResponse(json.dumps(response_data), mimetype="application/json"))
return response
如果我直接访问该地址,这似乎证实了头被设置正确
Access-Control-Allow-Origin:*
Content-Type:application/json
Date:Thu, 08 Mar 2012 05:06:25 GMT
Server:Apache/2.2.20 (Ubuntu)
Transfer-Encoding:chunked
然而在跨域设置它添加页眉Access-Control-Allow-Origin = *
总是失败(同时尝试Chrome和Firefox)。我试过正是因为每所选择的答案执行代码this的问题,但得到了同样的错误
更新
我敢肯定,问题是服务器端,因为我设法得到我的ajax调用与不同的公共CORS服务器一起工作。当我比较从这个公共服务器返回的头文件和从我的返回头文件(当我从同一个域中测试时)时,我看不到任何可能导致差异的主要差异(见下文)。
我排除的一个微妙之处,可能或可能很重要的是,实际域是多个子域的亚马逊域。 实际地址是http://ec2-23-20-27-108.compute-1.amazonaws.com/get_orders,随时探讨它,看看我做错了什么。
从公共服务器
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:622
Content-Type:text/html
Date:Thu, 08 Mar 2012 15:33:20 GMT
Keep-Alive:timeout=15, max=99
Server:Apache/2.2.14 (Ubuntu)
Vary:Accept-Encoding
X-Powered-By:Perl/5.8.7, PHP/4.4.0
从我的服务器 - (不工作跨域)
Access-Control-Allow-Origin:*
Content-Encoding:gzip
Content-Type:text/plain
Date:Thu, 08 Mar 2012 15:32:24 GMT
Server:Apache/2.2.20 (Ubuntu)
Transfer-Encoding:chunked
Vary:Accept-Encoding
我已经尝试过,为Json数据启用CORS并从未成功过。 CORS可以像这样片状。只要返回JSON-P就会好得多。 – xbonez 2012-03-08 06:36:29
您只在远程服务器和本地客户端之间发布_final_交换头。如果您查看完整的交换,我相信您会看到一个OPTIONS请求以及一个包含Access-Control-Allow-Methods和Access-Control-Allow-Headers标题的响应。 – 2012-03-10 16:40:31