获取“TypeError:无法获取”当请求实际上没有失败时 [英] Getting "TypeError: failed to fetch" when the request hasn't actually failed

查看:223
本文介绍了获取“TypeError:无法获取”当请求实际上没有失败时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的React应用中使用



但同时也会出现此错误。



  fetch(url) 
.then(res => res.json())
.then(data => {
//对数据执行某些操作
})
。 catch(已拒绝=> {
console.log(已拒绝);
});

当我删除凭证时:include ,它适用于localhost,但不适用于服务器。



我尝试了在StackOverflow和GitHub上给出的每个解决方案,但这对我来说没有用。

解决方案

问题可能在于您从后端收到的回复。如果它在服务器上正常工作,那么问题可能在于响应头。
检查响应标头中的 Access-Control-Allow-Origin (ACAO)。通常,当响应头的ACAO和请求的来源不匹配时,即使在接收到响应后,react的fetch API也将无法获取。


I'm using fetch API within my React app. The application was deployed on a server and was working perfectly. I tested it multiple times. But, suddenly the application stopped working and I've no clue why. The issue is when I send a get request, I'm receiving a valid response from the server but also the fetch API is catching an exception and showing TypeError: failed to fetch. I didn't even made any changes to the code and it's the issue with all of the React components.

I'm getting a valid response.

But also getting this error at the same time.

fetch(url)
.then(res => res.json())
.then(data => {
  // do something with data
})
.catch(rejected => {
    console.log(rejected);
});

When I remove credentials: "include", it works on localhost, but not on the server.

I tried every solution given on StackOverflow and GitHub, but it's just not working out for me.

解决方案

The issue could be with the response you are receiving from back-end. If it was working fine on the server then the problem could be with the response headers. Check the Access-Control-Allow-Origin (ACAO) in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' ACAO and the origin of request won't match.

这篇关于获取“TypeError:无法获取”当请求实际上没有失败时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆