【问题标题】:Javascript Post Request to different hostJavascript Post请求到不同的主机
【发布时间】:2013-06-25 13:02:56
【问题描述】:

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

【问题讨论】:

  • 不能,出于安全原因禁止,见here
  • 你可以在任何地方使用 from to POST...

标签: javascript post xmlhttprequest request


【解决方案1】:

除非您的浏览器支持 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');
}

【讨论】:

  • 我使用的是 ff22,所以它确实支持 CORS。如何判断远程主机是否允许来源?
  • 它正在工作。支持 CORS,但我没有得到任何响应。
【解决方案2】:

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

这允许您绕过谷歌浏览器中的同源策略并测试您的东西。

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2019-05-04
    • 1970-01-01
    • 2015-07-24
    相关资源
    最近更新 更多