I am trying to use an XMLHttpRequest to POST some data to a server (currently localhost, but will later be remote) and retrieve the response. I am using the Cross-origin-resource sharing method described here. However, I never receive the response data. The result is the same if I ignore the cross-origin issue and just send a normal XMLHttpRequest. I have verified using Postman that the URL sent is correct (JSON data is returned). Does anyone see what I am doing wrong here? Thanks very much!
// taken from StackOverflow
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function sendRequest() {
var theUrl = "http://localhost:4567/myApi?input="
+ encodeURIComponent("some text input");
alert(theUrl); // verified this is correct using Postman
var request = createCORSRequest("POST", theUrl);
if (request){
request.onreadystatechange = function() {
console.log(request); // shows responseText empty
alert("http returned " + request.responseText);
};
request.send();
}
}
The console.logged request looks like:
XMLHttpRequest {}
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: ()
ontimeout: null
readyState: 4
response: ""
responseText: ""
responseType: ""
responseURL: ""
responseXML: null
status: 0
statusText: ""
timeout: 0
upload: XMLHttpRequestUploadwithCredentials: false
__proto__: XMLHttpRequest