我已经看到这个问题被多个人问到,但没有一个答案对我有用。
我正在尝试使用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);
});
}
这是错误消息:
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.
我已经阅读了有关con CORS的文章,其他所有人都指向 https://www.html5rocks.com/zh-CN/tutorials/cors/
但我在那里找不到解决问题的答案。
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>
这是一个通过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>
像这样使用Maps JavaScript API(通过script
加载库的元素,然后使用google.maps.Map
和其他google.maps.*
方法)是从运行浏览器的前端JavaScript代码向Google Maps API发出请求的唯一受支持的方法。
Google故意不允许通过其他此类库中的使用axios或AJAX方法发送的请求(也不能直接使用XHR或Fetch API)访问Google Maps API。
知道SDK如何可以调用api端点而不会出现CORS错误吗?我尝试查看它调用的端点,并尝试直接从我的JavaScript调用它,但是它给了我CORS错误。只是想了解sdk如何绕过CORS
@ gaurav5430 SDK已从Google的域加载,因此可以访问它