0

I need this to return a value, but currently I don't get the console log "FetchNewsData() xhr.readyState started"(line 11), telling me that the if loop doesn't run, but why? Please help. Code is bellow.

var apiKey = "My_API_Key_Here";
      var query = "Boats";
      var url = "http://api.mediastack.com/v1/news?access_key=" + apiKey + "&keywords=" + encodeURIComponent(query) + "&limit=10";

      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {

          console.log("fetchNewsData() xhr.readyState started");

          var data = JSON.parse(xhr.responseText);
          displayNewsData(data.data);
        }
      };
      xhr.send();

      console.log("fetchNewsData() finished");
    }

I tried to change the url, and I tried to mess around with the xhr parameters, but Im not very good with xhr, so I probably missed something. I need the JSON.parse variable to be set, and I need the displayNewsData function to be called, but neither is happening.

  • Probably because the readyState never reaches 4 or the status never reaches 200. Look those values outside the `if` to see what values pass through it. Also check the Network tab to see what the response looks like. Also check the console for errors as it's unusual for an API key to be included in a URL in client-side code and that often indicates that the API is intended not be be accessed by browsers and so the browser will be throwing an error about lack of permission from CORS. – Quentin Mar 14 '23 at 15:41
  • @brk — That's a bad duplicate target. They aren't trying to return anything. (I think it needs to be closed as "needs debugging", but not as a duplicate). – Quentin Mar 14 '23 at 15:43

0 Answers0