【问题标题】:"No 'Access-Control-Allow-Origin' header is present on the requested resource." when making "GET" request“请求的资源上不存在‘Access-Control-Allow-Origin’标头。”发出“GET”请求时
【发布时间】:2018-12-12 18:41:28
【问题描述】:

我正在使用 HTTP 请求来获取 Google 的自动完成建议,这就是我这样做的灵感:

您可以向以下 URL 发出 GET 请求:

http://suggestqueries.google.com/complete/search?client=chrome&q=cats

其中“client”参数是您的浏览器名称(适用于大多数浏览器,但您可以传递>相同类型,而不管用户当前使用什么,它仍然可以工作)。

“q”参数是您的搜索字符串。

这将为您返回一个建议项目列表,然后您可以将其放入 jQuery 自动完成插件或构建您自己的(可悲的是,您不能让整个 >google 下拉界面弹出一个函数 :))

(src:Add Google autocomplete to Google search bar?)

我正在使用这个函数来获取谷歌的回复文本:

function httpGetAsync(theUrl, getGoogle){
   var xmlHttp = new XMLHttpRequest();
   xmlHttp.onreadystatechange = function() { 
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
         getGoogle(xmlHttp.responseText);
   }
   xmlHttp.open("GET", theUrl, true); // true for asynchronous
   xmlHttp.send(null);
}

但是,当函数执行时,CORS 似乎阻止我得到响应:Failed to load http://suggestqueries.google.com/complete/search?client=chrome&q=xx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

有没有办法在资源中添加“Access-Control-Allow-Origin”标头?

【问题讨论】:

  • 您的 theUrl 是否由网络服务器提供服务?
  • 也许http://suggestqueries.google.com 不允许您仅从客户端(浏览器)向服务器(服务器)发出请求 - 这就是它不发送 Access-Control-Allow-* 标头的原因

标签: javascript xml request cors http-headers


【解决方案1】:

您不能从用户浏览器向另一个域发出请求,除非源具有您域的 Access-Control-Allow-Origin 标头。总之,如果不使用某种代理,您就无法在用户部分发出请求,例如:

https://cors-anywhere.herokuapp.com/

例子:

url: https://cors-anywhere.herokuapp.com/https://google.com

【讨论】:

  • 非常感谢,此方法是否存在重大安全问题?
猜你喜欢
  • 2021-02-18
  • 2013-11-29
  • 2014-07-28
  • 2014-01-19
  • 2013-12-07
相关资源
最近更新 更多