首页 > 解决方案 > JavaScript访问谷歌地方API的CORS问题

问题描述

尝试了多种与标头的组合,以对谷歌地图 Places API进行 ajax jQuery 调用以获取预测。

我收到以下错误:

无法加载https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Amsterdam&types=geocode&key=AIzaSyBqYrYm377wh0pgINHBQfadjCokJkj_uVQ&_=1535634162773

对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ https://stackoverflow.com ”。

在控制台中执行以下代码时(URL 中没有 API 密钥):

jQuery.ajax({
    type: 'GET',
    url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Amsterdam&types=geocode&key={API Key Here}",
    contentType: "application/json",
    dataType: 'json',
    "crossDomain": true,
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Content-Range, Content-Disposition, Content-Description, x-requested-with, x-requested-by',
        "accept": "application/json",
        "Access-Control-Allow-Origin":"*"
    },
    success: postSuccess,
    error: postError,
});
function postSuccess(result,status,xhr) {
    console.log("postSuccess");
}
function postError(xhr,status,error) {
    console.log("postError", xhr,status,error);
}

如果有人能指出我的解决方案,那就太好了。

编辑:在问一个之前搜索了类似的问题,发现这个但解决方案没有帮助。

Edit2:更具体地说,我想从 JavaScript 中的 Places API 检索 JSON 结果:https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Amsterdam&types=geocode&key={API Key Here}

标签: google-maps

解决方案


要从 javascript 访问地点 API,请使用Google Maps Javascript API v3 地点库


推荐阅读