我想创建一个使用来自另一个域的 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/ http://enable-cors.org/)需要客户端和服务器双方的努力才能工作。我想假设 Weather Underground API 知道它在做什么,并且已经适当地启用了一些功能,例如设置响应标头以包含“Access-Control-Allow-Origin: *”,并且我知道当我使用另一个 API 提供商(世界天气在线)尝试相同的代码。所以我认为这是我应该能够在我的客户端代码中修复的问题。
另一个SO答案,建议修复服务器端标头:CORS 与 XMLHttpRequest https://stackoverflow.com/questions/14728418/cors-with-xmlhttprequest
我试图寻找答案,但不理解以下文章:http://dev.opera.com/articles/view/dom-access-control-using-cross-origin-resource-sharing/ http://dev.opera.com/articles/view/dom-access-control-using-cross-origin-resource-sharing/
http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/ http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/