首页 > 解决方案 > 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;
}

请帮我在我的获取请求中获取数据。任何建议将不胜感激。谢谢你。

标签: reactjsapifetch

解决方案


尝试

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


推荐阅读