I tried to fetch some data from my API with Cross-Origin enabled but got this error.
Same thing with JSONPlaceholder (an online REST API for testing) using an example they provide :
fetch('')
.then(response => response.json())
.then(json => console.log(json))
Both requests (JSONPlaceholder and my API) work fine using Insomnia (a REST client), so my guess is that the problem is in my React application (16.13.1).
After some tests, it seems that the error only occurs when calling the fetch function from a <form>
, here are some details :
handleSubmit = () => {
fetch('')
.then(response => response.json())
.then(json => console.log(json))
}
<form onSubmit={this.handleSubmit} >
<button type="submit">FETCH</button>
</form>
Thanks.
I tried to fetch some data from my API with Cross-Origin enabled but got this error.
Same thing with JSONPlaceholder (an online REST API for testing) using an example they provide :
fetch('https://jsonplaceholder.typicode./todos/1')
.then(response => response.json())
.then(json => console.log(json))
Both requests (JSONPlaceholder and my API) work fine using Insomnia (a REST client), so my guess is that the problem is in my React application (16.13.1).
After some tests, it seems that the error only occurs when calling the fetch function from a <form>
, here are some details :
handleSubmit = () => {
fetch('https://jsonplaceholder.typicode./todos/1')
.then(response => response.json())
.then(json => console.log(json))
}
<form onSubmit={this.handleSubmit} >
<button type="submit">FETCH</button>
</form>
Thanks.
I managed the reproduce your error. It seems like the network request is stopped when the page reloads. You could add a simple event.preventDefault
to stop the reload until the fetch
finishes and then reload the page.
handleSubmit = (event) => {
event.preventDefault()
fetch("https://jsonplaceholder.typicode./todos/1")
.then((response) => response.json())
.then((json) => {
console.log(json)
window.location.reload()
})
}
And of course you can also not reload the page at all for a better user experience :)