首页 > 解决方案 > 表单提交 ReactJS 上的“类型错误:尝试获取资源时出现网络错误”

问题描述

我尝试在启用跨域的情况下从我的 API 中获取一些数据,但出现此错误。使用他们提供的示例
JSONPlaceholder (用于测试的在线 REST API)相同:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

两个请求(JSONPlaceholder 和我的 API)都可以使用 Insomnia(一个 REST 客户端)正常工作,所以我的猜测是问题出在我的 React 应用程序(16.13.1)中。

编辑

经过一些测试,似乎该错误仅在从 a 调用 fetch 函数时发生<form>,这里有一些细节:

handleSubmit = () => {
   fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
}
<form onSubmit={this.handleSubmit} >
    <button type="submit">FETCH</button>
</form>

谢谢。

标签: javascriptreactjs

解决方案


我设法重现了您的错误。当页面重新加载时,网络请求似乎停止了。您可以添加一个简单event.preventDefault的停止重新加载,直到fetch完成,然后重新加载页面。

handleSubmit = (event) => {
  event.preventDefault()
  fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then((response) => response.json())
    .then((json) => {
      console.log(json)
      window.location.reload()
    })
}

当然,您也可以根本不重新加载页面以获得更好的用户体验:)


推荐阅读