为何Axios调用Google Place API报错但Postman正常?
我先通过geocode()获取目标坐标,再将其传入nearbySearch()调用Google Place API的nearbysearch接口查找周边地点,但控制台出现Axios跨域错误:
错误信息
从源'null'访问XMLHttpRequest到'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.7162525,-95.4169039&radius=500&key=AjzaSyD7LSZB-~
net::ERR_FAILED 200'被CORS策略阻止:请求的资源上不存在'Access-Control-Allow-Origin'头。
scripts.js:88 q {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
xhr.js:247 GET https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.7162525,-95.4169039&radius=500&key=AjzaSyD7LSZB-
用Postman直接调用该URL完全正常,尝试直接传入坐标而非变量lastCoordinates问题依旧,也验证了URL和API密钥的正确性。请问可能的问题有哪些?
相关JS代码
let lastCoordinates function geocode(){ axios.get('https://maps.googleapis.com/maps/api/geocode/json', { params:{ address: lastAddress, key:'AjzaSyD7LSZB-~~~~~~~~~~~~~~~~~~~~~~~' } }) .then(function(response){ console.log(response); endAddress = response.data.results[0].geometry.location; lastCoordinates = endAddress.lat + "," + endAddress.lng; }) .catch(function(error){ console.log(error); }) } nearbyBtn = document.getElementById('nearbyBtn'); nearbyBtn.addEventListener('click', nearbySearch); // Not working // function nearbySearch(){ axios.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json', { params:{ location: lastCoordinates, radius: 500, key:'AjzaSyD7LSZB-~~~~~~~~~~~~~~~~~~~~~~~' } }) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); }) }
1. 本地文件协议(file://)触发严格CORS限制
直接打开本地HTML文件时,浏览器URL以file://开头,此时页面源会被标记为null,浏览器的CORS策略会严格拦截跨域请求。而Postman不受浏览器CORS规则约束,所以能正常请求。
解决方法:
- 用本地服务器运行代码,比如执行
python -m http.server(Python3)、npx serve(Node.js),或使用XAMPP等工具,让页面通过http://localhost:端口号访问。
2. Google Places Web服务接口不支持浏览器端直接调用
你调用的nearbysearch/json属于Google Places Web服务接口,这类接口设计为服务器端调用,默认不允许浏览器端直接发起请求,会触发CORS限制。
解决方法:
- 改用官方推荐的浏览器端方案:Google Maps JavaScript SDK的
places.nearbySearch()方法,示例代码如下:// 先在HTML中引入SDK(需替换为你的API密钥) <script src="https://maps.googleapis.com/maps/api/js?key=你的API_KEY&libraries=places"></script> // JS中调用方法 function nearbySearch() { // 需先初始化地图实例 const map = new google.maps.Map(document.getElementById('map'), { center: {lat: endAddress.lat, lng: endAddress.lng}, zoom: 15 }); const service = new google.maps.places.PlacesService(map); service.nearbySearch({ location: new google.maps.LatLng(endAddress.lat, endAddress.lng), radius: 500 }, (results, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { console.log(results); } }); } - 若坚持用Web服务接口,需在自己的服务器端转发请求:浏览器请求自身服务器,由服务器调用Google API,再将结果返回给浏览器,绕开CORS限制。
3. 浏览器缓存或扩展干扰
浏览器缓存的旧响应、广告拦截/隐私类扩展可能会阻止跨域请求,导致CORS错误。
解决方法:
- 清除浏览器缓存,或用无痕模式打开页面测试。
- 暂时禁用浏览器扩展(如AdBlock、Privacy Badger等)后重试。
内容的提问来源于stack exchange,提问作者RussoB

