0

我想通过 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");
4

2 回答 2

0

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

这使您可以绕过 google chrome 中的相同来源策略并测试您的东西。

于 2013-07-03T23:18:16.503 回答
0

XHR 不可能,除非您的浏览器支持 CORS 并且远程主机允许您的来源(或允许所有来源 (*))。见这里

来自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');
}
于 2013-06-27T21:08:45.647 回答