javascript - 表单提交 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>
谢谢。
解决方案
我设法重现了您的错误。当页面重新加载时,网络请求似乎停止了。您可以添加一个简单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()
})
}
当然,您也可以根本不重新加载页面以获得更好的用户体验:)
推荐阅读
- python - 解压缩单词后重新创建图像以获取它们
- typescript - 如何禁止一个界面的按键出现在另一个界面
- c# - Selenium - StaleElementReferenceException (Chromedriver 80)
- dynamics-crm-365 - 从 CRM 迁移到云 365。Ribbon Workbench 导出解决方案
- azure - AzureStorageEmulator 5.1 无法启动
- mysql - SQL 将输出限制为多个结果
- angular - 从版本 2.9.2 更新到 3.7.5 后出现打字稿错误
- android - 如何动态更改底部导航项文本?
- css - 带有滚动角的粘性侧边栏
- go - 为什么golang对字节切片使用括号,对字符串切片使用括号?