Dark Sky API troubleshooting for local weather app

Dark Sky API troubleshooting for local weather app
0.0 0

#1

Hi! I’m still working on my local weather app. I have gotten a response from the Google Maps API to reverse geocode the coordinates that I get from the browser. I have tried to use that same code in a separate function to get a response from the Dark Sky API. Here is the code:

function getWeatherAPI (apiLinkDS) {
  var xhrW = new XMLHttpRequest();
  xhrW.open("GET", apiLinkDS);
  xhrW.send();
  console.log(xhrW.status);
  return JSON.parse(xhrW.responseText);
}

For that code I get absolutely no response from the server, but if I am looking at my API usage on my Dark Sky account, the calls are all there.

I have also tried using this code:

function getWeatherAPI (apiLinkDS) {
  var xhrW = new XMLHttpRequest();
  xhrW.open("GET", apiLinkDS);
  xhrW.onload = function() {
    if (xhrW.status === 200) {
        console.log('User\'s name is ' + xhrW.responseText);
    }
    else {
        console.log('Request failed.  Returned status of ' + xhrW.status);
    }
  }
  xhrW.send();
  console.log(xhrW.status);
  return JSON.parse(xhrW.responseText);
}

From this code I don’t get any sort of response from the if/else statement. I get a response from the second call to the console outside of the if/else, but it’s a response of 0. I have tried to google this response and haven’t been able to find much help. Anyone have any ideas?


#2

First, do you have this in a CodePen for review? If not, could you perhaps link to your code repository?

Second, I suggest ditching the xhr object. It’s frustrating and gross. The fetch api is the coming standard for all web browsers, so there’s little reason to struggle with xhr anyways. Fetch will allow you to handle errors and debug your code much faster.


Why i am getting XMLHttprequest status 0?
#3

Yup, fetch is so much easier and more comfortable to use.


#4

https://codepen.io/hellcatkate/pen/jVRbwG

Yes, xhr is gross :joy: This app has been so frustrating for me because it’s been taking me so long to complete, but working on it has forced me to learn about so many different things. Now to read up about fetch. Thank you!