XMLHttpRequest无法加载URL。 Access-Control-Allow-Origin不允许原点

时间:2013-09-11 05:11:36

标签: javascript xmlhttprequest cors

我想创建一个使用来自其他域的xml数据的小型网站。 (Weather Underground的天气数据:www.wunderground.com)。我只使用html和javascript,并在Visual Studio Express 2012 for Web中编写所有内容。

我按如下方式制作并发送xml请求:

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;

问题是我在Google Chrome(版本29.0.1547.66)开发者控制台中收到以下错误:

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. 

或者在Internet Explorer(版本10.0.8)控制台上:

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

据我了解,CORS(http://enable-cors.org/)需要客户端和服务器都努力工作。我想假设Weather Underground API知道它在做什么并且已经适当地启用了一些东西,例如将响应头设置为包含'Access-Control-Allow-Origin:*',我知道我在遇到同样的问题时我使用另一个API提供商(World Weather Online)尝试相同的代码。所以我认为这是我应该能够在我的客户端代码中修复的东西。 另一个SO答案建议是修复服务器端头: CORS with XMLHttpRequest

我试图找到答案,但不理解如下文章: http://dev.opera.com/articles/view/dom-access-control-using-cross-origin-resource-sharing/ http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/

1 个答案:

答案 0 :(得分:3)

相关问题