1

I am trying to make a fetch request for my React app, but I keep getting this CORS error. The request works fine in Postman. I have added the Access-Control-Allow-Origin header. I also tried adding mode: 'no-cors', but that did not work either. I can't find anything online for any other solutions. This is the code I'm using:

    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer <MY_API_KEY>");
    myHeaders.append("Cookie", "__cfduid=db290300ecfe95ec1fe3bc92c388c3c991586618117");
    myHeaders.append("Access-Control-Allow-Origin", "*");

    var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
    };

    fetch("https://api.yelp.com/v3/businesses/search?location=Houston", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
Leslie
  • 21
  • 1
  • 5

2 Answers2

1

The Access-Control-Allow-Origin is response header, it's mean that it does not matter in request, the server should allow to you make request.

is it API at yelp.com is allowed to you?

Kyr
  • 887
  • 7
  • 11
1

If you're simply looking to validate the Yelp api response then try running the request through a proxy that deals with the CORS policy for you like this:

var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <MY_API_KEY>");
myHeaders.append("Cookie", "__cfduid=db290300ecfe95ec1fe3bc92c388c3c991586618117");
myHeaders.append("Access-Control-Allow-Origin", "*");

var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
var targetUrl = 'https://api.yelp.com/v3/businesses/search?location=Houston'

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};


fetch(proxyUrl + targetUrl, requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
jcklopp
  • 451
  • 5
  • 9