【发布时间】:2013-11-07 18:28:04
【问题描述】:
我不明白为什么这个 CORS 请求无法返回数据。
我在后端使用 Catalyst MVC,Firefox 24.0 作为浏览器。 jQuery 1.9.1。请注意以下几点:
- otherdomain.com 需要客户端证书。
- 直接点击资源会返回预期的数据。 (https://otherdomain.com/resource/1) 返回正确的数据。
我有一个测试请求的简单页面:
<script type='text/javascript'>
function get_data() {
console.log("running");
$.ajax({
url: "https://otherdomain.com/resource/1",
dataType: 'json',
type: 'GET',
xhrFields: {
'withCredentials': true
},
crossDomain: true
}).success(function(data) {
console.log(data)
$('#output').html(data);
}).error(function(xhr, status, error) {
alert("error");
console.log(xhr);
});
}
$(document).ready(function() {
get_data();
});
</script>
</script>
这是我的请求标头:
GET /resource/1 HTTP/1.1
Host: otherdomain.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: https://mydomain.com/test.html
Origin: https://mydomain.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
这是我的响应标头。 (来自 firebug 控制台的视图源副本)我在催化剂调试输出中看到请求作为 200 OK 并发送了内容。
HTTP/1.1 200 OK
Date: Mon, 28 Oct 2013 19:31:08 GMT
Server: HTTP::Server::PSGI
Vary: Content-Type
Content-Length: 653
Content-Type: application/json
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 1800
X-Catalyst: 5.90030
Via: 1.1 otherdomain.com
并且错误是从 ajax 调用中抛出的:
readyState: 0
responseText: ""
status: 0
statusText: "error"
firebug 将请求事件中的响应正文显示为空,尽管它是 200 OK。
我认为在使用“withCredentials”时需要飞行前请求,但我没有看到通过 firebug 发送 OPTIONS。
另外,我看不到我的请求没有添加Access-Control-Request-Header,所以我没有从服务器返回任何Access-Control-Allow-Headers。
现在,Catalyst 的前端是 Apache2,我在虚拟主机中使用 proxypass 将请求发送到 localhost:8080 上的 Catalyst。我不确定这是否有任何影响,但我认为这可能很重要。不过它应该对浏览器是透明的。
感谢您的帮助!
【问题讨论】:
-
对于面临这个问题的asp.net核心用户,请使用:services.AddCors();然后 app.UseCors( options => { options.WithOrigins(" * or a domain name here ").AllowAnyMethod(); options.AllowCredentials(); } );
标签: jquery ajax cross-domain cors