Google Maps API:请求的资源上没有"Access-Control-Allow-Origin"标头

jai*_*fps 7 google-maps xmlhttprequest google-maps-api-3 cors axios

我已经看到多个人提出这个问题了,没有一个答案对我有用.

我正在尝试使用react/axios对google maps api进行API调用.

这是我的获取请求:

componentDidMount() {
  axios({
   method : 'get',
   url : `http://maps.googleapis.com/maps/api/js?key=${key}/`,
   headers: {
     "Access-Control-Allow-Origin": '*'
     "Access-Control-Allow-Methods": 'GET',
   },
  })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
}
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/js?
key=xxxxxxxxx/. Response to preflight request doesn't pass access control 
check: No 'Access-Control-Allow-Origin' header is present on the 
requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

我读过其他人都指向https://www.html5rocks.com/en/tutorials/cors/的文章con CORS

但我找不到我的问题的答案.

sid*_*ker 16

https://maps.googleapis.com/maps/api 不支持以您的代码尝试使用它的方式从Web应用程序中运行的前端JavaScript获取请求.

相反,您需要使用受支持的Google Maps JavaScript API,其客户端代码与您尝试的不同.一对距离矩阵服务样本看起来更像是这样的:

<script>
  var service = new google.maps.DistanceMatrixService;
  service.getDistanceMatrix({
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
},…
</script>

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Run Code Online (Sandbox Code Playgroud)

以下是使用Places库使用Place Autocomplete API的示例:

<script>
  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });
    ...
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);
    var infowindow = new google.maps.InfoWindow();
    var infowindowContent = document.getElementById('infowindow-content');
    infowindow.setContent(infowindowContent);
    var marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });
</script>
<script
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
  async defer></script>
Run Code Online (Sandbox Code Playgroud)

使用Maps JavaScript API(通过script元素加载库,然后使用google.maps.Map其他google.maps.*方法)是唯一支持从运行浏览器的前端JavaScript代码向Google Maps API发出请求的方法.

Google故意不允许通过其他此类库中的axios或AJAX方法发送的请求访问Google Maps API,也不允许直接使用XHR或Fetch API访问Google Maps API.

  • @Phil 这不是真的,脚本一旦加载,就会在当前域上下文中执行,并且对 google api 端点的任何调用都将来自当前域,而不是托管脚本的域。在这种情况下,他们似乎使用 jsonp 来绕过 CORS (2认同)