I am trying to make an AJAX POST call in an API using Javascript. It gives me this error
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
Below is the code causing this error
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));
calculating url and variable is completely fine. Converting to JSON is fine too. I tried converted JSON with HTTP client (RESTED). It worked fine, so the error in the POST call is most likely due to headers and resource sharing Cross origin (CORS).
When I use the HTTP client, this is the response header with which I successfully collaborate
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
Any idea what is going on here? Why doesn’t it work through the browser? I tried this in Safari and Chrome.