我正在尝试使用Javascript对API进行AJAX POST调用。它给了我这个错误
OPTIONS https://ethor-prod.apigee.net/v1/stores/HI6PIDO5JS/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers. store.js:581
calculateorder store.js:581
onclick index-3.html:183
XMLHttpRequest cannot load https://ethor-prod.apigee.net/v1/stores/HI6PIDO5JS/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7.
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers. index-3.html:1
以下是导致此错误的代码
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
alert("success");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE, PUT, HEAD");
xmlhttp.setRequestHeader("Access-Control-Max-Age","1728000");
xmlhttp.send(JSON.stringify(calculate));
网址和变量计算完全正常。转换为JSON也很完美。我尝试使用HTTP客户端(RESTED)转换JSON。它工作得很好,所以错误在POST调用中,很可能与头文件和跨源资源共享(CORS)有关。
当我使用HTTP客户端时,这是我与成功执行相关的响应头
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Access-Control-Allow-Origin: *
Set-Cookie: JSESSIONID=DC0DBDB6B877BD1CD67BBE4E20432BFD; Path=/v1.0/; HttpOnly
Server: nginx/1.4.5
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT, HEAD
Transfer-Encoding: Identity
Access-Control-Max-Age: 1728000
Access-Control-Allow-Headers: x-requested-with
Expires: Mon, 10 Mar 2014 21:20:44 GMT
Cache-Control: max-age=0
Date: Mon, 10 Mar 2014 21:20:44 GMT
Content-Encoding: gzip
Vary: Accept-Encoding
有什么想法发生在这里吗?为什么不通过浏览器工作?我在Safari和Chrome上都尝试过它。