如何解决Google Routes API调用时出现的404错误?
Google Routes API 404错误排查与修复
核心原因:请求体格式不符合Routes API要求
你混淆了Google Routes API和Directions Matrix API的参数规则——computeRoutes接口(Routes API v2)是单起点单终点路由接口,不支持Matrix API的origins/destinations数组参数,必须使用origin和destination结构化字段。
代码中的具体问题及修复
错误的请求体参数结构
原代码用了Matrix API的参数格式,这是导致404的直接原因之一:// 错误写法(Matrix API格式) const requestBody = { origins: [`${directionsFrom}`], destinations: [`${directionsTo}`], // ...其他参数 };替换为Routes API要求的结构(每个点需用
address或location对象包裹):// 正确写法(Routes API格式) const requestBody = { origin: { address: directionsFrom }, destination: { address: directionsTo }, travelMode: 'DRIVE', routingPreference: 'TRAFFIC_AWARE', unitSystem: 'IMPERIAL' };冗余的CORS请求头
你添加的Access-Control-Allow-Origin、Access-Control-Allow-Methods等是服务器端才需要设置的响应头,前端请求时不需要加这些,反而可能干扰请求,直接删除:headers: { 'Content-Type': 'application/json' // 只保留这个必要头即可 }API权限检查
确认你的API密钥已在Google Cloud控制台中单独启用了Routes API服务——哪怕密钥能在Matrix API中正常使用,Routes API的权限是独立的,未启用会导致权限类错误(可能表现为404或403)。
额外排查建议
- 查看网络面板的完整响应:点击请求条目,切换到
Response标签页,通常能看到更详细的错误提示(比如参数格式错误的具体描述)。 - 验证URL正确性:v2版本的
computeRoutes端点https://routes.googleapis.com/v2:computeRoutes是正确的,确保没有拼写错误。
修正后的请求示例片段
fetch(routesApiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ origin: { address: directionsFrom }, destination: { address: directionsTo }, travelMode: 'DRIVE', routingPreference: 'TRAFFIC_AWARE', unitSystem: 'IMPERIAL' }) }) .then(response => { // 主动处理非成功响应,获取详细错误信息 if (!response.ok) { return response.text().then(errText => { throw new Error(errText) }); } return response.json(); }) .then(data => { // 注意Routes API的响应结构和Matrix不同,需调整渲染逻辑 const route = data.routes[0]; // 时长是ISO 8601格式字符串,如"PT15M"(15分钟) const duration = route.duration; // 距离单位是米,需自行转换为英制单位 const distanceMiles = (route.distanceMeters / 1609.34).toFixed(2); // 后续渲染逻辑... }) .catch(error => { console.error('Routes API请求错误:', error); });
内容的提问来源于stack exchange,提问作者Julius Goddard
相关产品推荐
相关产品推荐

