第三方API跨域请求(https)

Posted

技术标签:

【中文标题】第三方API跨域请求(https)【英文标题】:Cross domain request of a third party API (https) 【发布时间】:2017-04-30 01:26:32 【问题描述】:

这是我试图从中获取 JSON 的网址: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”标头。 Origin 'null' >因此不允许访问。

我也试过 JSONP,但好像不支持 JSONP。

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

【问题讨论】:

如果站点未配置为允许跨域请求,您必须在您控制的服务器上使用服务器端代理。您无法通过浏览器中的 javascript 执行任何操作。 当@Pointy 提到代理时,他的意思是help.shopify.com/api/tutorials/application-proxies @Pointy 你有教程链接吗? @singard 上面评论中有人发布的链接怎么样? @SomeoneSpecial 这个链接看起来我需要在 shopify 上设置一个应用程序? 【参考方案1】:

出现问题是因为 XMLHTTPRequest 导致 CORS 问题。应从浏览器对同一域进行 XMLHTTPRequest 调用。

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

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

【讨论】:

以上是关于第三方API跨域请求(https)的主要内容,如果未能解决你的问题,请参考以下文章

简单理解jsonp原理

对jsonp原理理解

Vue axios调用第三方接口跨域解决

第三篇微信小程序-网络请求API

vue跨域配制

Reactjs之Axiosfetch-jsonp获取后台数据