2
votes

I have this API call working in Postman, but when I copy the code into my JS code I get the following error:

XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=40.82783908257346&longitude=-74.10162448883057.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
The response had HTTP status code 500.

My AJAX call (with Bearer altered for security):

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=40.82783908257346&longitude=-74.10162448883057",
  "method": "GET",
  "headers": {
    "authorization": "Bearer xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "cache-control": "no-cache",
    // "postman-token": "1c66878e-c740-e10d-8d9a-71d731547d2e"
  }
}


$.ajax(settings).done(function (response) {
  console.log(response);

According to the Yelp documentation - Yelp does not support CORS - so CORS is not the issue.

1
Possible duplicate of How to allow CORS?Ben Aubin

1 Answers

0
votes

I was able to implement it without any issues on the client-side using Fetch. I suspect it might be one of your headers.

fetch('https://api.yelp.com/oauth2/token?client_id=<CLIENT_ID>&client_secret=<CLIENT_SECRET>', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: JSON.stringify({
    grant_type: 'client_credentials',
  })
})
  .then((res) => res.json())
  .then((resJSON) => {
    this.setState({ access_token: resJSON.access_token });
    console.log(resJSON)
  })
  .then(() => {
    fetch('https://api.yelp.com/v3/businesses/search?location=12345', {
      method: 'GET',
      headers: {
        'authorization': 'Bearer ' + this.state.access_token
      }
    })
    .then((res) => res.json())
    .then((resJSON) => {
      console.log('resJSON', resJSON)
    })
  })
  .catch((err) => {
    console.log('err', err);
  })