继续使用XMLHttpRequest获取No'Access-Control-Allow-Origin'错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了继续使用XMLHttpRequest获取No'Access-Control-Allow-Origin'错误相关的知识,希望对你有一定的参考价值。
我会通过使用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不允许使用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
以上是关于继续使用XMLHttpRequest获取No'Access-Control-Allow-Origin'错误的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript/Ajax:如果 XMLHttpRequest() 在 x 秒后失败,则继续
XMLHttpRequest 无法加载 XXX No 'Access-Control-Allow-Origin' 标头
XMLHttpRequest 无法加载 XXX No 'Access-Control-Allow-Origin' 标头
XMLHttpRequest 无法加载 XXX No 'Access-Control-Allow-Origin' 标头