1

I am having a little trouble with parsing the data. When i add JSON.parse(this.responseText) and this.status == 200 on the if statement my code seem to not work. When I take them off it works and I get the alert that it's a success. Not sure what I am doing wrong or maybe I am doing it completely wrong lol any help will be greatly appreciated! I am using Yelp API.

Here is my code:

    xhr.withCredentials = true;
    
    xhr.onreadystatechange = function() {
      if(this.readyState == 4) {
        console.log(this.responseText);
        //let data = JSON.parse(this.responseText);
        alert("Success!");
        //display(data);
      }
    };
    
    xhr.open("GET", "https://api.yelp.com/v3/businesses/search?term=" + resname.value + "&location=" + locationname.value+"&limit=5");
    xhr.setRequestHeader("Authorization", "Bearer <MY API KEY WILL BE HERE>");
    xhr.send();

error when I parse:

Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.xhr.onreadystatechange 
lxx2015
  • 23
  • 4
  • You said it not working means is it giving any error – SidPro Dec 09 '20 at 04:49
  • This is the error I get: index.html:1 Access to XMLHttpRequest at 'https://api.yelp.com/v3/businesses/search?location=NYC' from origin 'http://127.0.0.1:5500' 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. api.yelp.com/v3/businesses/search?location=NYC:1 I get the success alert when i take off the json.parse( this is the error when i add JSON.parse Unexpected end of JSON input at JSON.parse () at XMLHttpRequest.xhr.onreadystatechange – lxx2015 Dec 09 '20 at 05:02

1 Answers1

1

Fusion API appears to have been developed with the intention for back-end use as there is no current "approved" method of using Fusion via JavaScript. Accordingly, Ajax requests from the front-end result in CORS (Cross Origin Resource Sharing violation) issues, as neither CORS headers nor the JSONP workarounds are supported by Fusion (at least not at the time of this writing).here

How do I resolve the CORS error in Yelp API call? same as yours error

EDIT: try this it work:

var queryURL = https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=food&location=New York City&limit=5;
var mykey = "";

        $.ajax({
            url: queryURL,
            method: "GET",
            headers: {
                "accept": "application/json",
                "x-requested-with": "xmlhttprequest",
                "Access-Control-Allow-Origin":"*",
                "Authorization": `Bearer ${mykey}`
             },
            success: function(result){
                console.log(result);
            }
         });
SidPro
  • 164
  • 1
  • 11