Javascript发布请求到不同的主机

时间:2013-06-27 21:03:22

标签: javascript post xmlhttprequest request

我想通过JavaScript将POST请求发送到具有一些请求标头和帖子正文的其他主机。

我该怎么做?

我尝试使用XMLHttpRequest,但是我收到以下错误: 0x80004005 (NS_ERROR_FAILURE)

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", "https://somedomain/deviceapi/v1/rest/registration/device/anonymous", false);
xmlHttpRequest.setRequestHeader("Accept", "application/json");
xmlHttpRequest.setRequestHeader("some key", "some value");
xmlHttpRequest.setRequestHeader("Accept-Charset", "UTF-8");
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlHttpRequest.send("some data");

2 个答案:

答案 0 :(得分:0)

除非您的浏览器支持CORS且远程主机允许您的源(或允许所有来源(*)),否则XHR无法使用。请参阅here

来自html5rocks.com的此功能会让您知道:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {

    // Check if the XMLHttpRequest object has a "withCredentials" property.
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    // Otherwise, check if XDomainRequest.
    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    // Otherwise, CORS is not supported by the browser.
    xhr = null;

  }
  return xhr;
}

var xhr = createCORSRequest('GET', url);
if (!xhr) {
  throw new Error('CORS not supported');
}

答案 1 :(得分:0)

cd C:\Program Files (x86)\Google\Chrome\Application\ chrome.exe --allow-file-access-from-files --disable-web-security pause

这允许您绕过谷歌浏览器中的相同原始策略并测试您的内容。