Tuesday, December 31, 2019

Electron JS - CORS error



Weird CORS error issues were happening when dealing with Electron JS. When trying to do from the renderer process, always receive CORS error.

To debug this, attempted to do the request using XMLHTTPRequest, which is like this below

 var oReq = new XMLHttpRequest();
    oReq.onload = this.reqListener;
    oReq.onerror = this.reqError;
    oReq.open('get', 'https://api.myjson.com/bins/j9soc', true);
    oReq.send();

reqListener() {
    console.log('reqListener called');
    var data = JSON.parse(this.responseText);
    console.log(data);
  }
 
  reqError(err) {
    console.log('reqError called');
    console.log('Fetch Error :-S', err);
  }

The site hosted a sample JSON and that was coming properly without issues.

Now, the same attempting to do with the fetch api, This was also successful.

fetch('https://api.myjson.com/bins/j9soc')
      .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('Fetch response received successfully without CORS!');
            console.log(data);
          });
        }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

Now decided to do the same from the service class and see what happens.

Surprisingly from Saga also received the response.

References

No comments:

Post a Comment