JSON parse not working properly - Javascript

285 views Asked by At

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 
1

There are 1 answers

2
SidPro On

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);
            }
         });