使用 xhr 请求 Google Place API 遇到了 CORS 问题

Requesting Google Place API with xhr got CORS issue

本文关键字:遇到 CORS 问题 API Place xhr 请求 Google 使用      更新时间:2023-09-26

在我的网页上,我有一些javascript代码来查询Google Place API(GET)的响应。这是我的代码如下所示:

// Sending XHR request
var url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=KPMG+Seattle&key=<<MY_KEY>>';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send();
//**********************//
// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } 
  else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } 
  else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

我在浏览器中运行此本地HTML文件,并收到CORS错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access. The response had HTTP status code 405.

我想知道问题可能是什么(我在请求标头中添加了访问控制允许来源)?
根据谷歌教程,这应该足以提出请求吗?

请帮助指出我做错的地方...谢谢!

请参阅这篇文章 XMLHttpRequest Origin null 是不允许

的基本上,如果您

从本地文件运行,则需要禁用一项安全功能以允许不同来源的 XHR。

请参阅帖子中的第一个答案。