Making fetch API work with CORS after OPTIONS response

letsc picture letsc · May 3, 2017 · Viewed 33.1k times · Source

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?

Answer

sideshowbarker picture sideshowbarker · May 4, 2017

The immediate problem you’re hitting is that your code as currently written expects the response to be JSON but the response is actually a Promise that you need to handle in order 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))