fetch() with the Wikipedia API results in “TypeError: NetworkError when attempting to fetch resource.”

徘徊边缘 提交于 2019-12-11 14:38:02

问题


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()



来源:https://stackoverflow.com/questions/37333573/fetch-with-the-wikipedia-api-results-in-typeerror-networkerror-when-attempti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!