Tuesday, December 31, 2019

Electron JS why XHR works but not fetch()





You're making a cross-origin request (your requesting domain is different than the API's domain) and browsers have special rules around that. In a Node context (i.e. via node's http/https modules), you don't have to worry about CORS and can in general do lower level work on network requests. Browsers, on the other hand, have a lot of security around CORS. When you use fetch your network request is going through Chromium's networking layer and so it's subject to those restrictions. When you use node's http/https, you're using node's. It's sort of a confusing point about Electron--a renderer process seems like a normal web context but you actually have access to all of node.js' APIs too, allowing you to things you can't do in a plain browser.

I would check and see if including an API key in that request changes the response of the API (maybe that triggers their API adding the appropriate CORS headers like Access-Control-Allow-Origin). Maybe the API wasn't meant to be called within a browser context and so a more node.js oriented approach is the way to go.

This is a great article on CORS and the ways to deal with it: https://medium.com/@baphemot/understanding-cors-18ad6b478e2b


References:
https://stackoverflow.com/questions/48969495/in-javascript-how-do-i-should-i-use-async-await-with-xmlhttprequest

How to make GET request with XHR, Promise

Define the API like this below

var remoteCode = await this.getServerResponse('https://api.myjson.com/bins/j9soc');

getServerResponse(url) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.setRequestHeader('Accept','application/json');
        xhr.setRequestHeader('Authorization','bWNkLWFkbWluOkFkbWluMUAxMjM');
        xhr.responseType = 'text';
        xhr.onload = function () {
            var status = xhr.status;
            console.log('XHR status is '+status);
            if (status == 200) {
                resolve(xhr.responseText);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
}


Refereces

No comments:

Post a Comment