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

Nuxt3/Vue项目调用Google Matrix API遇CORS跨域错误求助

解决Google Distance Matrix API的CORS问题(Nuxt3/Vue环境)

问题原因

Google Distance Matrix API不支持直接从前端浏览器发起跨域请求,浏览器的同源策略会拦截这类请求,导致出现access-control-allow-origin缺失的CORS错误。直接在地址栏能访问是因为地址栏请求不受同源策略限制,和API Key无关。

解决方案:通过Nuxt3服务器代理请求

在Nuxt3中,我们可以创建服务器端API路由作为代理,由后端发起对Google API的请求,再将结果返回给前端,这样既规避CORS问题,也能保护API密钥不暴露在前端。

步骤1:创建服务器API路由

在项目根目录的server/api文件夹下新建distance.js文件,编写代理逻辑:

export default defineEventHandler(async (event) => {
  // 获取前端传递的参数
  const { town, center } = getQuery(event);
  // 从环境变量读取Google API密钥(避免前端暴露)
  const apiKey = process.env.GOOGLE_MAPS_API_KEY;

  // 参数校验
  if (!town || !center || !apiKey) {
    return createError({ statusCode: 400, statusMessage: '缺少必要参数' });
  }

  // 构造Google Distance Matrix API请求地址,注意编码参数
  const requestUrl = `https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${encodeURIComponent(town)}&origins=${encodeURIComponent(center)}&units=imperial&key=${apiKey}`;
  
  // 发起后端请求(Nuxt3内置$fetch,无需额外安装)
  const apiData = await $fetch(requestUrl);
  
  // 处理API返回的错误状态
  if (apiData.status !== 'OK') {
    return createError({ statusCode: 500, statusMessage: apiData.error_message || '获取距离失败' });
  }

  // 返回距离数值
  return apiData.rows[0].elements[0].distance.value;
});

步骤2:配置环境变量

在项目根目录创建.env文件,添加你的Google API密钥:

GOOGLE_MAPS_API_KEY=你的实际API密钥

确保.env文件已添加到.gitignore中,防止密钥泄露到代码仓库。

步骤3:修改前端调用逻辑

将原来直接请求Google API的代码,改为请求我们的服务器代理接口:

const getDistance = async (town, center) => {
  // 编码参数,避免特殊字符问题
  const encodedTown = encodeURIComponent(town);
  const encodedCenter = encodeURIComponent(center);
  
  const response = await fetch(`/api/distance?town=${encodedTown}&center=${encodedCenter}`);
  
  if (!response.ok) {
    throw new Error('获取距离失败,请稍后重试');
  }
  
  const distanceValue = await response.json();
  return distanceValue;
};

额外注意事项

  • 确保你的Google API密钥已启用Distance Matrix API权限,否则会返回权限错误。
  • 后端代理请求时记得对参数进行encodeURIComponent编码,避免因特殊字符导致请求地址无效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:45:36