You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中调用Google Places Nearby Search API无法获取JSON数据导致地点名称无法显示的问题求助

解决谷歌Places API跨域请求失败及内容不显示问题

看起来你踩了谷歌Places API的一个常见坑——浏览器端直接请求会触发CORS跨域限制,这就是控制台报错CORS header ‘Access-Control-Allow-Origin’ missing的原因,最终导致数据拿不到,div里自然显示不了内容。下面给你两种可行的解决方案:

一、后端代理请求(推荐,同时保护API密钥)

谷歌这类API设计的初衷是让请求从后端服务器发起,这样既绕开了浏览器的同源策略,还能避免把你的API密钥暴露在前端代码里(防止被盗用产生高额费用)。

1. 写一个简单的后端代理接口(以Node.js/Express为例)

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

app.get('/api/nearby-places', async (req, res) => {
  // 把API密钥存在后端,绝对不要暴露给前端
  const apiKey = '你的真实API密钥';
  const { location, radius, type, keyword, maxprice } = req.query;
  
  try {
    const response = await axios.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json', {
      params: { location, radius, type, keyword, key: apiKey, maxprice }
    });
    res.json(response.data);
  } catch (error) {
    res.status(error.response?.status || 500).json({ error: '请求失败,请检查API配置' });
  }
});

app.listen(PORT, () => console.log(`代理服务器运行在端口 ${PORT}`));

2. 修改前端fetch请求地址

把原来直接请求谷歌API的地址换成你的后端代理接口:

const [business1, setbusiness1] = useState(null); 

useEffect(() => { 
  fetch('http://localhost:3001/api/nearby-places?location=-33.8943,151.2330&radius=1000&type=restaurant&keyword=attractions&maxprice=4') 
    .then(response => response.json()) 
    .then(data => { 
      // 加个判断,避免数组为空时报错
      if (data.results?.length > 0) {
        setbusiness1(data.results[0].name);
      } else {
        setbusiness1('未找到附近符合条件的地点');
      }
      console.log("返回数据", data.results);
    })
    .catch(err => console.error('请求出错:', err)); // 别忘了捕获错误
}, []);

⚠️ 注意:谷歌Places API的maxprice参数是0(最便宜)到4(最贵)的整数,不是你之前写的1000,这个参数需要修正!

二、使用谷歌Maps JavaScript API的Places库

如果你的项目本来就在用谷歌地图的前端库,可以直接用它提供的Places服务来发起请求,这种方式不会有CORS问题:

1. 先在HTML中引入谷歌Maps JS API(包含places库)

<script async defer src="https://maps.googleapis.com/maps/api/js?key=你的API密钥&libraries=places"></script>

2. 修改React组件中的请求逻辑

const [business1, setbusiness1] = useState(null); 

useEffect(() => {
  // 确保谷歌地图库加载完成再执行
  if (window.google?.maps.places) {
    // 创建一个临时div用于初始化服务(不需要渲染到页面)
    const service = new window.google.maps.places.PlacesService(document.createElement('div'));
    
    const request = {
      location: new window.google.maps.LatLng(-33.8943, 151.2330),
      radius: 1000,
      type: ['restaurant'],
      keyword: 'attractions',
      maxPriceLevel: 4 // 同样注意这里是0-4的整数
    };

    service.nearbySearch(request, (results, status) => {
      if (status === window.google.maps.places.PlacesServiceStatus.OK && results.length > 0) {
        setbusiness1(results[0].name);
        console.log("返回数据", results);
      } else {
        setbusiness1('请求失败或无匹配地点');
        console.error('请求状态:', status);
      }
    });
  }
}, []);

额外提醒

  • 无论用哪种方式,都要确保你的谷歌云账户已经启用了Places API,并且API密钥配置了合理的限制(比如IP限制、HTTP referrer限制),防止被恶意调用。
  • 绝对不要在前端代码里直接写API密钥,后端代理是更安全的做法。

内容的提问来源于stack exchange,提问作者Jim N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:12:27