【发布时间】:2014-10-08 14:20:12
【问题描述】:
我会通过使用 jQuery $.ajax 函数来解决这个问题,但在这种情况下,jQuery 不是选项。相反,我将使用 CORS 请求。我觉得响应请求的网络服务器有问题,我很难找出问题所在。
这是我创建 CORS 请求的代码
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');
httpRequest.setRequestHeader( 'Content-Type', 'application/json' );
httpRequest.onerror = function(XMLHttpRequest, textStatus, errorThrown) {
console.log( 'The data failed to load :(' );
console.log(JSON.stringify(XMLHttpRequest));
};
httpRequest.onload = function() {
console.log('SUCCESS!');
}
这是 console.log 错误:
XMLHttpRequest 无法加载 http://test.testhost.com/testpage。请求头域 Access-Control-Allow-Origin 不允许 访问控制允许标头。
这是标题信息:
> Remote Address:**.**.***.**:80 Request
> URL:http://test.testdomain.com/testpage Request
> Request Method:OPTIONS
> Status Code:200 OK
请求标头:
OPTIONS /content-network HTTP/1.1
Host: test.testhost.com
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: POST
Origin: http://test.testdomain.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin, content-type
Accept: */*
Referer: http://test.testdomain.com/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
响应标头:
HTTP/1.1 200 OK
Date: Thu, 14 Aug 2014 20:17:25 GMT
Server: Apache
Last-Modified: Thu, 14 Aug 2014 20:17:25 +0000
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
ETag: "1408047445"
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Vary: Accept-Encoding
Content-Encoding: gzip
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Content-Length: 6117
Connection: close
Content-Type: text/html; charset=utf-8
【问题讨论】:
-
Access-Control-Allow-Origin是在 服务器响应 中发送的标头,indicates that the client is allowed to see the contents of a result;它不是用于请求访问资源的请求标头。不要在您的请求中发送Access-Control-Allow-Origin。 -
@apsillers 我已将 Header set Access-Control-Allow-Origin * 添加到 appache 中的 .htaccess、vhost 和 httpd.conf - 无济于事,并且启用了 apache 模块、标头、IS .
-
non-simple request headers here 的使用(
Access-Control-Allow-Origin不是简单的标头——也不应该由客户端发送——而application/json是Content-Type的非简单值) 浏览器正在发送a preflight OPTIONS request,以检查服务器是否通过Access-Control-Allow-Headers允许这些请求标头。 -
@apsillers - 我已经用新的标题编辑了我的问题,我现在得到了 200 个响应,但是控制台中的 JS 出现了同样的错误。 ajax 和 XDomainRequest 不会发生此错误,但这不再是一个选项。
-
@apsillers - 再次编辑它们,如果以前没有,它们现在是正确的。
标签: javascript xmlhttprequest cors response