【问题标题】:React fetch failed: "TypeError: Failed to fetch" even though the API returns dataReact fetch failed: "TypeError: Failed to fetch" 即使 API 返回数据
【发布时间】:2019-07-09 09:02:02
【问题描述】:

我有一个使用 React fetch 的 Web API 请求,但收到一个错误:“TypeError: Failed to fetch”。

我在 Web API 中设置了一个断点,它返回的数据没有任何错误。所以我认为问题出在 React 中的客户端站点。

这是我的 API(项目是 Web API core 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;
}

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

【问题讨论】:

    标签: reactjs api fetch


    【解决方案1】:

    试试

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

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 1970-01-01
      • 2018-04-03
      • 2020-07-10
      • 1970-01-01
      • 2020-09-18
      • 2017-08-02
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多