Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest cannot load URL. Origin not allowed by Access-Control-Allow-Origin

I want to make a small website that uses xml data from another domain. (Weather data from Weather Underground: www.wunderground.com). I am using just html and javascript, and writing it all in Visual Studio Express 2012 for Web.

I make and send the xml request as follows:

url = "http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml";

xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;

The problem is that I get the following error in the Google Chrome (version 29.0.1547.66) developer console:

XMLHttpRequest cannot load http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml. Origin http://localhost:49933 is not allowed by Access-Control-Allow-Origin. 

Or this on Internet Explorer (version 10.0.8) console:

SEC7118: XMLHttpRequest for http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml required Cross Origin Resource Sharing (CORS). 

As I understand it, CORS (http://enable-cors.org/) needs effort by both the client and the server to work. I want to assume that the Weather Underground API knows what it is doing and has enabled things appropriately, such as setting the response header to include 'Access-Control-Allow-Origin: *', and I know that I get the same problems when I try the same code using another API provider (World Weather Online). So I think this is something I should be able to fix in my client code. Another SO answer where the suggestion is to fix the server-side header: CORS with XMLHttpRequest

I have tried to find answers, but don't understand articles such as: http://dev.opera.com/articles/view/dom-access-control-using-cross-origin-resource-sharing/ http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/

like image 403
Scott Newson Avatar asked Sep 11 '13 05:09

Scott Newson


1 Answers

Use Ajax with JSONP if you want in jquery

For javascript see here , http://developer.chrome.com/extensions/xhr.html and http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

Use .json format data rather than .xml to make your application simpler and faster i.e http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.json

like image 73
Prasath K Avatar answered Oct 15 '22 19:10

Prasath K