第三方API的跨域请求(https)

时间:2016-12-14 16:17:18

标签: javascript json cors cross-domain jsonp

这是我试图从https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6

获取JSON的网址

但是,我已经尝试了两个CORS但它失败了。以下是我在模板中的代码:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {
  var url = 'https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function () {
    var text = xhr.responseText;
    console.log("success");
  };

  xhr.onerror = function () {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}
makeCorsRequest();

它仍然给我这个错误:

  

XMLHttpRequest无法加载&gt; https://shopicruit.myshopify.com/admin/orders.json?&gt; page = 1&amp; access_token = c32313df0d0ef512ca64d5b336a0d7c6。请求的资源上不存在“Access-Control-&gt; Allow-Origin”标头。因此,不允许原点'null'&gt;访问。

我也尝试过JSONP,但看起来它不支持JSONP。

任何帮助和见解将不胜感激!

1 个答案:

答案 0 :(得分:0)

问题发生是因为XMLHTTPRequest导致CORS问题。 XMLHTTPRequest调用应该从浏览器调用到同一个域。

https://shopicruit.myshopify.com必须在响应中实施 Access-Control-Allow-Origin:* 标头才能从所有域访问。

否则,您可以将服务器用作代理。