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

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

问题描述

我在我的 React 应用程序中使用

但同时也得到这个错误:

fetch(url).then(res => res.json()).then(数据=> {//对数据做一些事情}).catch(拒绝 => {控制台日志(拒绝);});

当我删除凭据:include"时,它适用于本地主机,但不适用于服务器.

我尝试了 StackOverflow 和 GitHub 上给出的所有解决方案,但对我来说并不奏效.

解决方案

问题可能与您从后端收到的响应有关.如果它在服务器上运行良好,那么问题可能出在响应标头上.检查响应标头中的 Access-Control-Allow-Origin.通常,当响应头的 Access-Control-Allow-Origin 和请求的来源不匹配时,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 make 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 in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' Access-Control-Allow-Origin and the origin of request won't match.

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

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