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

4.1k Views Asked by At

First of all, I was using this (maybe old) code in 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 -- 
    }
}

This code solved the problem. Until this URL came:

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

The first error I encountered is:

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.

To not change anything in the browser, long searches have led me to the fetch() function. But I categorically cannot understand how to get a response from the server in the form of JSON or at least in the form of text (for further conversion to JSON)

I try this:

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);  
  });

And I get the answer:

Looks like there was a problem. Status Code: 0

Is there any way to get the data? It is desirable in a variable. Because I just do not understand how fetch works.

I just need to get data from the API for further processing.

2

There are 2 best solutions below

2
On BEST ANSWER

You still have problem with cors. Mode "no-cors" just does not work as you expecting.

0
On

What you're dealing with is Cross-Origin Resource Sharing (CORS). The URL you're requesting the data from doesn't allow the data to be fetched from another domain. The reason your second snippet works is because you set the mode to no-cors. The call will succeed but your code won't be able to access any of the data. It is kinda useless for your purpose.