reactjs - React fetch failed: "TypeError: Failed to fetch" 即使 API 返回数据
问题描述
我有一个使用 React fetch 的 Web API 请求,但收到一个错误:“TypeError:无法获取”。
我在 Web API 中设置了一个断点,它返回的数据没有任何错误。所以我认为问题出在 React 中的客户端站点。
这是我的 API(该项目是 Web API 核心 2.2):
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
//I set a break point here and it return value below
return new string[] { "value1", "value2" };
}
}
这是我在 React 中的获取请求:
testButton = async function () {
const json = await fetch('https://localhost:44365/api/values/',
{
method: 'GET',
credentials: 'include',
mode: 'cors'
})
.then(response => response.json())
.catch(function(e) {
console.log("error");//the error comes here (e = TypeError: Failed to fetch)
});
return json;
}
请帮我在我的获取请求中获取数据。任何建议将不胜感激。谢谢你。
解决方案
尝试
const testButton = async function () {
const json = await fetch('https://localhost:44365/api/values/',
{
method: 'GET',
credentials: 'include',
mode: 'cors'
})
if (json.ok) {
const resp = await res.json()
console.log(resp)
}
}
testButton();
推荐阅读
- python - 结果仅作为最后一个结果附加到列表
- java - 存在多个java bean类时如何设置值
- php - 来自文本的 PHP 正则表达式电子邮件地址,有时在句号之前
- json - 为什么我无法使用 Kotlin 读取 json 文件 rom 资源文件夹?
- openid-connect - H2O Steam 与 Apache Knox 的集成
- javascript - 传播运算符与 immutable.js
- java - Spring boot bcrypt.BCryptPasswordEncoder 和身份验证问题
- r - 如何使用 R 中的 ExtremeBounds 包将极端边界分析应用于包含 100 多个变量的数据集?
- outlook - c# winforms: 打开outlook收件箱页面的按钮(outlook保存在电脑中)
- javascript - Highcharts/Highstock 标志系列问题