fetch() with the Wikipedia API results in “TypeErr

2019-07-26 16:44发布

问题:

fetch('https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json')
    .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) {  
        document.write('Fetch Error :-S', err);  
    });

The fetch address I'm using is listed here: https://www.mediawiki.org/wiki/API:Main_page under simple sample. Currently it catches on the error on the bottom with TypeError: NetworkError when attempting to fetch resource. So far I've been unable to access any data from the API after trying different things with fetch()

Any help would be appreciated!

The project is on codepen here: http://codepen.io/javascriptisscary/pen/RazKWB

回答1:

The problem is due to fetch() using CORS. However, when I changed to mode: "no-cors" I was no longer blocked on Cross-origin request but given a status code of 0.

According to this documentation from google: https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en

" 'no-cors' is intended to make requests to other origins that do not have CORS headers and result in an opaque response, but as stated, this isn’t possible in the window global scope at the moment."

So currently to access the wikipedia api, one will have to use a different way than fetch()