1

Im making an API call(Running on another domain) using Fetch in a React Web app. I am getting the error Following error.

Access to fetch at '--------API URL---------' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have also read several answers on StackOverflow about the same issue, titled "Access-Control-Allow-Origin" but still couldn't figure out how to solve this. I don't want to use an extension IN Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.

my code looks like this.

{
        return fetch('-----------API URL--------',
        {   method:'GET',
            mode: 'cors',
            headers:{
                'Access-Control-Allow-Origin':'*'
            },
        })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson.ALLORDERSRX);
            this.setState({
                isLoading: false,
                dataSource: responseJson.ALLORDERSRX,
            }, function(){

            });
        })
        .catch((error) =>{
            console.error(error);
        });

    }
Ranjitha R
  • 21
  • 1
  • 1
  • 6
  • In simple words: You are trying to access a different url (in your case a localhost with different port) then the url that served your react application. You can solve this by changing your server side code to both serve the app AND listen to API requests. – RtmY Mar 11 '19 at 08:28

1 Answers1

5

const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = 'https://api.liveconnect.in/backend/web/erpsync/get-all-orders?data=dbCode=UAT04M%7Cidx=100%7CuserId=6214%7Cres_format=1'; // site that doesn’t send Access-Control-*
fetch(proxyurl + url).then((resp) => resp.json())
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log(error);
  }); 

found from here :No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Saurabh Mistry
  • 11,077
  • 4
  • 41
  • 64