如何使用 Fetch API 跨源加载 Javascript 中的文本或 JSON 数据?

How to use the Fetch API cross-origin to load text or JSON data in Javascript?

首先,我在 Javascript 中使用了这个(可能是旧的)代码:

function GetJson(url)
{
    // 1. New Object XMLHttpRequest
    var xhr = new XMLHttpRequest();

    // 2. Config it 
    xhr.open('GET', url, false);

    // 3. Send request
    xhr.send();

    // 4. Errors 
    if (xhr.status != 200) {
        // Responce error out
        return( xhr.status + ': ' + xhr.statusText ); // 404: Not Found
    } else {
        // Responce result
        return( xhr.responseText ); // responseText -- 
    }
}

这段代码解决了这个问题。直到 URL 出现:

https://bittrex.com/api/v1.1/public/getmarketsummaries/

我遇到的第一个错误是:

XMLHttpRequest can not load https://bittrex.com/api/v1.1/public/getmarketsummaries/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file: //' is therefore not allowed access.

为了不改变浏览器中的任何内容,长时间的搜索使我找到了 fetch() 函数。但我绝对无法理解如何以 JSON 的形式或至少以文本的形式从服务器获得响应(以便进一步转换为 JSON)

我试试这个:

fetch('https://bittrex.com/api/v1.1/public/getmarketsummaries/',{mode:'no-cors'})  
  .then(  
    function(response) {  
      if (response.status !== 200) {  
        console.log('Looks like there was a problem. Status Code: ' +  
          response.status);  
        return;  
      }

      // Examine the text in the response  
      response.json().then(function(data) {  
        console.log(data);  
      });  
    }  
  )  
  .catch(function(err) {  
    console.log('Fetch Error :-S', err);  
  });

我得到了答案:

Looks like there was a problem. Status Code: 0

有什么方法可以获取数据吗?在变量中是可取的。因为我就是不明白 fetch 是怎么工作的。

我只需要从 API 中获取数据以进行进一步处理。

你的 cors 还是有问题。模式 "no-cors" 并没有像您预期的那样工作。

您正在处理的是跨源资源共享 (CORS)。您请求数据的 URL 不允许从其他域获取数据。您的第二个代码段起作用的原因是您将模式设置为 no-cors。调用会成功,但您的代码将无法访问任何数据。它对您的目的有点无用。