You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

加载Google Place API失败,遇CORS跨域访问错误求助

解决Google Places API的CORS错误问题

我之前开发时也碰到过完全一样的CORS问题,给你几个实际可行的解决方案,按推荐程度排序:

1. 使用官方Google Places JavaScript API(最推荐)

Google专门提供了前端用的JavaScript库,已经帮我们处理好了CORS的问题,不需要自己手动发HTTP请求。步骤如下:

首先在你的HTML页面中引入API库(记得替换成你的API key):

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAdLYQ6qjosGg82jMH2jymB6XS_tWRKHpE&libraries=places"></script>

然后在JavaScript里调用nearbySearch方法:

function fetchNearbyPlaces() {
  // 创建一个PlacesService实例(需要一个DOM元素,这里临时创建一个div)
  const service = new google.maps.places.PlacesService(document.createElement('div'));
  
  // 构造请求参数
  const request = {
    location: new google.maps.LatLng(12.938008, 77.5790956),
    radius: 100000,
    keyword: 'visiting places near me'
  };

  // 发送请求并处理结果
  service.nearbySearch(request, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      // 这里可以拿到所有返回的地点数据,按需处理
      console.log('找到的地点:', results);
    } else {
      console.error('请求失败:', status);
    }
  });
}

// 页面加载完成后执行
window.addEventListener('load', fetchNearbyPlaces);

这个方法是官方支持的,不仅解决CORS问题,还能直接使用Google Maps的其他功能,比如地点详情、地图渲染等。

2. 搭建后端代理服务器

如果你的项目本来就有后端服务,可以通过后端转发请求来绕过浏览器的同源策略(服务器之间没有CORS限制)。这里给个Node.js + Express的简单示例:

首先安装依赖:

npm install express axios

然后写代理服务器代码:

const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3001;

// 定义代理接口
app.get('/api/nearby-places', async (req, res) => {
  try {
    const apiKey = 'AIzaSyAdLYQ6qjosGg82jMH2jymB6XS_tWRKHpE';
    // 从前端请求中获取参数
    const { location, radius, keyword } = req.query;
    // 构造Google Places API的请求地址
    const googleApiUrl = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${location}&radius=${radius}&keyword=${keyword}&key=${apiKey}`;
    
    // 后端请求Google API
    const response = await axios.get(googleApiUrl);
    // 将结果返回给前端
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: '请求Google API失败', details: error.message });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`代理服务器运行在 http://localhost:${PORT}`);
});

然后前端请求自己的代理接口即可:

fetch('http://localhost:3001/api/nearby-places?location=12.938008,77.5790956&radius=100000&keyword=visiting+places+near+me')
  .then(response => response.json())
  .then(data => console.log('地点数据:', data))
  .catch(error => console.error('请求失败:', error));

⚠️ 注意:不要把API key暴露在前端代码里,通过后端代理可以很好地保护你的key,上线后记得给API key设置合适的限制(比如IP地址限制,只允许你的后端服务器访问)。

3. 不推荐:使用no-cors模式

错误提示里提到的no-cors模式虽然能绕过CORS检查,但浏览器会把响应标记为透明响应(opaque response),你无法读取响应的具体内容——只能知道请求成功了,但拿不到地点数据。如果你的需求只是触发请求而不需要处理结果,这个方法才有用,否则完全不适合。

示例代码:

fetch('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=12.938008,77.5790956&radius=100000&keyword=visiting+places+near+me&key=AIzaSyAdLYQ6qjosGg82jMH2jymB6XS_tWRKHpE', {
  mode: 'no-cors'
})
.then(response => {
  // 这里无法调用response.json(),因为响应是opaque的
  console.log('请求状态:', response.status); // 只能看到状态码,看不到数据
});

额外检查项

  • 确保你的API key已经启用了Places API权限(在Google Cloud控制台里查看);
  • 如果设置了API key的HTTP referrers限制,本地开发时可以暂时添加http://localhost:3000到允许列表,上线后替换成你的生产域名。

内容的提问来源于stack exchange,提问作者kranti kumar

火山引擎 最新活动