Force fetch API to work with CORS after OPTIONS response

I am trying to fetch data from our API. The API has enabled CORS support and returns below response to 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 constraint, I am trying to use a fetch

React-Native method 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 guess this is because CORS only allows one of the three headers by default. However, because the server does not support this content type, it returns an error for an unsupported content type.

Method 2 (with a corso or nothing):

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

      

In this case, using the Chrome F12 networking tool, I see the server returning data: the first request to the server is fetch

for OPTIONS

. To do this, the server replies back with an empty object along with the above sets of headers. The next call is the actual API POST call, to which the server responds with an appropriate JSON response containing some data. However, the answer that appears on the console via my code is {}

. I assume this is because the React API is fetch

returning the call response OPTIONS

instead of the actual call POST

.

Is it possible to ignore the OPTIONS request response and get a method then

to handle the subsequent request response?

+6


source to share


1 answer


The immediate problem you are facing is that your code is currently expecting a response as JSON, but the response is actually a promise that you need to process in order to receive JSON.

So, you need to do something like this:



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

      

+16


source







All Articles