Making fetch API work with CORS after OPTIONS response

41,120

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))
Share:
41,120
letsc
Author by

letsc

I am a noob to programming... So please ignore my poor programming skills and help me gain from your cognizance.. :)

Updated on August 11, 2021

Comments

  • letsc
    letsc over 2 years

    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?