E
E
Evgeny Kolman2019-09-01 22:44:18
JavaScript
Evgeny Kolman, 2019-09-01 22:44:18

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.
5d6c1d9fc4a6d582914480.png
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
5d6c1e775b0d6451015648.png
. If in then I receive res.json(), I get the following error
5d6c1f3bdfe24817218018.png
. 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

1 answer(s)
H
hzzzzl, 2019-09-02
@hzzzzl

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.

https://stackoverflow.com/a/43319482
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 question

Ask a Question

731 491 924 answers to any question