Answer the question
In order to leave comments, you need to log in
What is the correct way to use fetch to get the correct json?
good afternoon.
There was such a situation.
I'm calling my endpoint(rest) to get a list of my data.
Here is my code on the client that receives data.
When I make a request, nothing is written in the browser console, but in the Network the status is 200 and the response received from the server.
I output the "received" data to the console and get an empty array of objects
. If in then I receive res.json(), I get the following error
. Here I understand that in fetch we must process an empty response?
Can anyone come across such a difficulty and can help figure out how to use fetch correctly?
Thank you very much in advance!
Answer the question
In order to leave comments, you need to log in
that's the thing
You need to remove the mode: 'no-cors' setting from your request. That mode: 'no-cors' is exactly the cause of the problem you're having.
A mode: 'no-cors' request makes the response type opaque. The console-log snippet in the question clearly shows that. And opaque means your frontend JavaScript code can't see the response body or headers.
fetch('http://....')
.then(res => res.json())
.then(res => {
this.setState({loaded: true, items: res.items})
})
.catch(err => {
console.log('OH SHIT:', err)
this.setState({loadError: true})
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question