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

使用Axios调用Google Place Autocomplete API时遭遇CORS错误

解决Google Place Autocomplete API的CORS错误问题

你直接在前端用Axios调用Google的Place Autocomplete API触发CORS限制,其实这是Google API的设计规则——他们的这类REST接口不支持直接从浏览器端发起请求,必须通过后端代理或者改用官方的浏览器端API来绕开这个限制。下面给你几个实用的解决办法:

1. 改用Google Places JavaScript API(最推荐)

Google专门为浏览器环境提供了Places JavaScript API,它内置处理了跨域逻辑,不需要你手动写请求。可以这样改造你的代码:

首先在HTML中引入官方脚本(替换成你的API Key):

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

然后修改TypeScript类,使用官方的自动完成服务:

export default class GoogleRequester {
  private autocompleteService: google.maps.places.AutocompleteService | null = null;

  constructor(apiKey: string) {
    // 确保API脚本加载完成后初始化服务
    if (typeof google !== 'undefined' && google.maps?.places) {
      this.autocompleteService = new google.maps.places.AutocompleteService();
    } else {
      throw new Error('Google Places API脚本未加载完成');
    }
  }

  placesAutocomplete(query: string): Promise<google.maps.places.QueryAutocompletePrediction[]> {
    return new Promise((resolve, reject) => {
      if (!this.autocompleteService) {
        reject(new Error('自动完成服务未初始化'));
        return;
      }

      this.autocompleteService.getQueryPredictions(
        { input: query },
        (predictions, status) => {
          if (status === google.maps.places.PlacesServiceStatus.OK && predictions) {
            resolve(predictions);
          } else {
            reject(new Error(`自动完成请求失败: ${status}`));
          }
        }
      );
    });
  }
}

这个方案是最稳妥的,毕竟是Google官方针对浏览器场景设计的,完全不会有CORS问题。

2. 搭建后端代理服务器

如果一定要用Axios发起请求,你需要在自己的后端(比如Node.js/Express)写一个代理接口,前端请求你的后端接口,再由后端转发请求到Google API。

举个Node.js+Express的代理示例:

// 后端代码
const express = require('express');
const axios = require('axios');
const app = express();

app.get('/api/places-autocomplete', async (req, res) => {
  const { query, apiKey } = req.query;
  try {
    const response = await axios.get('https://maps.googleapis.com/maps/api/place/queryautocomplete/json', {
      params: {
        key: apiKey,
        input: query
      }
    });
    res.json(response.data);
  } catch (error) {
    res.status(error.response?.status || 500).json(error.response?.data || { error: '请求失败' });
  }
});

app.listen(3000, () => console.log('代理服务器运行在3000端口'));

然后前端修改请求地址,指向你的代理接口:

// 前端TypeScript代码修改
placesAutocomplete(query: string) {
  // 替换成你的代理接口地址
  const requestUrl = `http://localhost:3000/api/places-autocomplete?key=${this.apiKey}&input=${encodeURIComponent(query)}`;
  return axios.get(requestUrl);
}

后端发起的请求不受浏览器同源策略限制,就能正常拿到Google API的返回数据了。

补充:为什么会出现CORS错误?

简单来说,浏览器的同源策略会阻止前端脚本直接请求不同域名的资源,除非目标服务器返回了允许跨域的HTTP头。而Google的Place Autocomplete REST API并没有配置允许前端域名跨域的响应头,所以直接在浏览器调用就会触发CORS错误。

内容的提问来源于stack exchange,提问作者Victor Castro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:58:32