在我的网页上,我有一些 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.
我想知道问题是什么(我在请求 header 中添加了 Access-Control-Allow-Origin)?
根据Google Tutorial这应该足以提出请求吗?
请帮忙指出我做错的地方......谢谢!
最佳答案
请看这篇文章XMLHttpRequest Origin null is not allowed
基本上,如果您从本地文件运行,则需要禁用一项安全功能才能允许不同来源的 XHR。
请参阅帖子中的第一个答案。
关于javascript - 使用 xhr 请求 Google Place API 遇到 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674796/