Warm tip: This article is reproduced from serverfault.com, please click

javascript-请求的资源错误中不存在“Access-Control-Allow-Origin”标头

(javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource error)

发布于 2015-02-16 17:45:17

我正在尝试获取新闻网站的提要。以为我会使用谷歌的提要 API 将提要燃烧器提要转换为 json。以下 url 将从提要中以 json 格式返回 10 个帖子。http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/mathrubhumi

我使用以下代码来获取上述网址的内容

$.ajax({
  type: "GET",
  dataType: "jsonp",
  url: "http://ajax.googleapis.com/ajax/services/feed/load",
  data: {
    "v": "1.0",
    "num": "10",
    "q": "http://feeds.feedburner.com/mathrubhumi"
  },
  success: function(result) {
    //.....
  }
});

但它不起作用,我收到以下错误

XMLHttpRequest 无法加载 http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http%3A%2F%2Ffeeds.feedburner.com%2Fmathrubhumi请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost '。

我该如何解决?

Questioner
Aneeez
Viewed
0
12.7k 2015-12-06 16:18:10

我相信这可能是 Chrome 不支持localhost通过Access-Control-Allow-Origin--参见 Chrome 问题

要让 Chrome 发送Access-Control-Allow-Origin标头,只需将 /etc/hosts 文件中的 localhost 别名为其他域,例如:

127.0.0.1   localhost yourdomain.com

然后,如果你使用yourdomain.com而不是访问你的脚本localhost,则调用应该会成功。