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

3

这是我正在尝试获取JSON的URL: https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6

然而,我已经尝试了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无法加载>https://shopicruit.myshopify.com/admin/orders.json?>page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6。所请求的资源上没有'Access-Control-Allow-Origin'头。因此,来自'null'的请求不被允许访问。

我还尝试了JSONP,但它似乎不支持JSONP。

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


1
如果网站没有配置允许跨域请求,您将需要在您控制的服务器上使用服务器端代理。在浏览器中,您无法从JavaScript中进行任何操作。 - Pointy
1
当 @Pointy 提到代理时,他指的是这个:https://help.shopify.com/api/tutorials/application-proxies - Someone Special
@Pointy,你有可以跟着学习的教程链接吗? - singard
@singard,你觉得上面评论里那个链接怎么样? - Pointy
你可以在任何想要的服务器上设置一个服务器端代理;这只是其中一种可能性。你已经有某种类型的服务器正在提供你正在工作的页面。 - Pointy
显示剩余3条评论
1个回答

0
问题出现是因为XMLHTTPRequest引起了CORS问题。应该从浏览器向同一域名发出XMLHTTPRequest调用。 https://shopicruit.myshopify.com必须在响应中实现Access-Control-Allow-Origin : *头,以便从所有域访问。
否则,您可以使用您的服务器作为代理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接