Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  9] [ 4]  / answers: 1 / hits: 44432  / 7 Years ago, wed, may 3, 2017, 12:00:00

I are trying to fetch data from our API. The API has enabled CORS support and returns the below response to the OPTIONS request:



Access-Control-Request-Headers:content-type  
Access-Control-Allow-Origin:*


The API doesn't allow 'Content-type' anything other than 'application/json'.



Using this limitation, I am trying to use the fetch method of React-Native to get the data.



Method 1 (no-cors):



{
method: 'POST',
mode: no-cors,
headers: {
'content-type': 'application/json'
}


With this method, the browser automatically sends the content-type as 'text/plain'. I assume this is because CORS allow just one of the three headers by default. However, since the server doesn't support this content-type, it returns an error back for unsupported content type.



Method 2 (with cors or with nothing):



{ 
method: 'POST',
mode: cors, // or without this line
redirect: 'follow',
headers: {
'content-type': 'application/json'
}
}
...
.then(response => console.log(response))


In this scenario, using Chrome's F12 network tool, I can see the server returning data : the first request to the server is a fetch for OPTIONS. To this, the server replies back with an empty object along with the above headers set. The next call is the actual POST API call, to which the server responds back with a proper JSON response containing some data. However, the response which is getting on the console via my code is {}. I assume this is because the react's fetch API is returning back the response of the OPTIONS call instead of the actual POST call.



Is there any way to ignore the response of the OPTIONS request and get the then method to process the response of the subsequent request?


More From » reactjs

 Answers
13

The immediate problem you’re hitting is, your code as currently written expects the response to be JSON but the response is actually a Promise that you need to handle to get the JSON.


So you need to instead do something like this:


fetch("https://example.com")
.then(response => response.json())
.then(jsondata => console.log(jsondata))

[#57914] Monday, May 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darrylm

Total Points: 499
Total Questions: 131
Total Answers: 108

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;