【问题标题】:XMLHttpRequest cannot load URL. Origin not allowed by Access-Control-Allow-OriginXMLHttpRequest 无法加载 URL。 Access-Control-Allow-Origin 不允许的来源
【发布时间】:2013-09-15 00:00:38
【问题描述】:

我想制作一个使用来自另一个域的 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/

【问题讨论】:

  • 你检查了他们设置的标题吗?
  • 我直接在 Chrome 中打开你的 url,开发者工具告诉我没有返回 Access-Control-Allow-Origin 标头。
  • 开发规则 1:不要假设其他人所做的事情是为了让您的生活更轻松。查看他们的 API 文档。 JSON、XML 和 JSONP - 带有示例。没有提到CORS。使用 JSONP。
  • @Passerby 谢谢,我不知道你能做到。

标签: javascript xmlhttprequest cors


【解决方案1】:

【讨论】:

  • 我的回复不是jsonp,是json..我该怎么办??
  • @SweetWisherツ 不管是什么,如果你向跨域发送请求,你的响应应该是jsonp类型
  • 我在 JSON 中而不是在 JSONP 中的响应
  • @SweetWisherツ 试试吧
猜你喜欢
  • 2012-09-28
  • 1970-01-01
  • 2012-05-25
  • 2013-01-24
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多