Retrieve temperature from weather service - JS

Hello,

I’ve been working on this way too long now and can’t figure it out. I want to be able to display the current temperature in a city, from the Environment Canada data, on my website. I’ve been through their maze of pages about the maps and api and such, but I can’t find anything basic enough for what I need. (I have been able to get a map with precipitation radar overlaid, which I would have thought would be more complicated than simply getting a temperature, but I digress.)

I found an xml document that contains the data I want, but when I try to fetch it with a script I get CORS error for same origin policy. Unfortunately, I need the data from this specific source (I’ve been able to get the Visual Crossing API to work in the interim). Any help figuring out how to accomplish this task would be much appreciated!

Cheers,

Can you share the code you are trying to fetch with? Using postman I have no problem accessing the xml information.

I honestly have no idea how to go about it, when I tried a while ago I just copy/pasted something from online. Now I’m going through the intermediate JS course and just started using the fetch() function, so I thought I’d try again, but I got the familiar CORS error. Right now I have this:

fetch('https://dd.weather.gc.ca/citypage_weather/xml/ON/s0000430_e.xml').then(response => {
  if (response.ok) {
    return response.json();
  }
  throw new Error('Request failed!');
  }, networkError => console.log(networkError.message)
  ).then(jsonResponse => {
      
});

I am looking into this still, but beside the potential CORS issue, you are trying to parse xml with json parsing functions. I know you will need to use other methods to pull the data out of the potential response. For example:

 let xml = new window.DOMParser().parseFromString(data, "application/xml");
1 Like

Aye, I was planning on figuring out what exactly to do with the data once I was able to actually get it haha. But that’s helpful! Thank you :slight_smile:

Ok, not sure of your overall implementation, but I think you are stuck unless you can get some help from the service itself.

Or you can consider one of the methods listed in this post regarding the issue: CORS Issue

The node proxy sounds promising, but not sure how that would work as I am not that experienced myself.

1 Like

Hm, yeah I guess I’ll try sending them an email and see if they have some insight, and I’ll play around with the stackoverflow methods too. I’ll update here if I figure something out. Thanks for the replies!

Cheers,

The page provides the HTML code for embedding a widget.

1 Like

This is very helpful! Thank you, I don’t know how I didn’t come across it. Not sure if it will work exactly how I want but it will be a great solution in the meantime.

Cheers!