在Javascript中向localhost发送跨源POST请求

时间:2015-10-19 09:36:09

标签: javascript http-post cross-domain

我正在尝试使用XMLHttpRequest将一些数据发送到服务器(当前是localhost,但稍后将是远程的)并检索响应。我正在使用here描述的跨源资源共享方法。但是,我从未收到过响应数据。如果我忽略跨源问题并且只发送一个普通的XMLHttpRequest,结果是一样的。我已使用Postman验证发送的URL是否正确(返回JSON数据)。谁有人在这看到我做错了什么?非常感谢!

// 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();
    }
}

console.logged请求如下所示:

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

0 个答案:

没有答案