【问题标题】:fetch() with the Wikipedia API results in "TypeError: NetworkError when attempting to fetch resource."使用 Wikipedia API 的 fetch() 会导致“尝试获取资源时出现类型错误:网络错误”。
【发布时间】:2016-09-16 22:40:30
【问题描述】:
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);  
    });

这里列出了我正在使用的获取地址:https://www.mediawiki.org/wiki/API:Main_page 在简单示例下。目前它使用TypeError: NetworkError when attempting to fetch resource. 捕获底部的错误到目前为止,在尝试使用 fetch() 进行不同操作后,我无法从 API 访问任何数据

任何帮助将不胜感激!

该项目在 codepen 上:http://codepen.io/javascriptisscary/pen/RazKWB

【问题讨论】:

标签: javascript fetch wikipedia-api


【解决方案1】:

问题是由于 fetch() 使用 CORS。但是,当我更改为 mode: "no-cors" 时,我不再因跨域请求而被阻止,而是状态码为 0。

根据谷歌的这份文档:https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en

" 'no-cors' 旨在向没有 CORS 标头的其他来源发出请求并导致不透明的响应,但如上所述,目前在窗口全局范围内这是不可能的.

因此,目前要访问 wikipedia api,必须使用与 fetch() 不同的方式

【讨论】:

  • 您说它已修复:'当我更改为模式时:"no-cors"。'你究竟是如何解决这个问题的?我在您的问题或其他任何地方都看不到“模式”。
【解决方案2】:

上面的答案是正确的。至于在哪里设置“模式”的评论只需这样做:

 fetch(url, { mode: 'no-cors' })

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2017-07-31
    • 2020-04-20
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多