1

在 Google 和 Stackoverflow 上花费了许多小时而没有任何进展的感觉之后,我正在寻求帮助以使交叉请求 ajax 正常工作。

我在客户端有 JQuery 和基本身份验证的自定义配置:

//configuration AJAX  
$(document).ajaxSend(function(e, xhr, options) {   
    xhr.withCredentials = true;  
    xhr.setRequestHeader("Authorization", "Basic dGVzdEB0ZXN0LmZyOmF6ZXJ0eQ==");  
});

//a request
$.get("http://domainA.com/api");

在我的服务器上,Apache 配置为使用特殊的 cors 标头进行响应:

Header always set Access-Control-Allow-Origin "http://domainB.com"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Request-Headers "Authorization, X-Requested-With, Content-Type, Accept, Origin"
Header always set Access-Control-Max-Age "86400"
Header always set Access-Control-Allow-Credentials "true"

因此,当请求发送时,AJAX 发出了预检请求:

OPTIONS /api HTTP/1.1
Host: domainA.com
User-Agent: useragent
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Origin: domainB.com
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Connection: keep-alive

我的服务器响应:

HTTP/1.1 200 OK
Date: Fri, 09 Aug 2013 15:58:38 GMT
Server: Apache
Access-Control-Allow-Origin: http://domainB.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Request-Headers: authorization, X-Requested-With, Content-Type, Accept, Origin
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true
Content-Length: 489
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1

并且 AJAX 请求停止而不做真正的请求。返回的代码是 0。我找不到配置中的问题,因为任何配置Access-Control-Request都有响应。谢谢您的帮助

4

1 回答 1

1

也许你应该试试这个?它在我的 Apache 服务器上运行良好:

Header always set Access-Control-Allow-Headers "Authorization, X-Requested-With, Content-Type, Accept, Origin"

使用Access-Control-Allow-Headers而不是Access-Control-Request-Headers.

于 2013-11-18T07:22:13.060 回答