Flutter Web调用Google API时的CORS错误修复咨询
解决Flutter Web(Firebase Hosting)调用Google Places API的CORS问题
问题本质
你配置的Firebase Hosting CORS规则仅对Firebase自有服务(比如Storage)生效,Google Places API是第三方服务,它的CORS响应头由Google控制,你无法通过Firebase的规则修改。浏览器的同源策略会阻止前端直接请求这类未允许你域名的第三方API,这就是报错的核心原因。
可行解决办法
1. 改用Google Maps JavaScript API官方组件
Google Places API本身推荐前端使用官方JS组件而非直接调用REST接口,组件已内置处理CORS和认证逻辑:
- 在Flutter Web的
web/index.html中引入Google Maps JS脚本:<script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥&libraries=places"></script> - 可以通过
dart:js桥接调用Autocomplete组件,或者使用适配Flutter的第三方包(如google_maps_flutter_web)实现地址自动补全,完全避开CORS问题。
2. 用Firebase Cloud Functions做代理
搭建后端代理,让前端请求你的Cloud Functions,再由Functions转发请求到Google Places API:
- 创建Cloud Function示例(Node.js):
const functions = require("firebase-functions"); const axios = require("axios"); exports.placeAutocomplete = functions.https.onRequest(async (req, res) => { const { input, types, sessiontoken, language, components } = req.query; const apiKey = "你的Google API密钥"; const targetUrl = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${input}&types=${types}&key=${apiKey}&sessiontoken=${sessiontoken}&language=${language}&components=${components}`; try { const apiResponse = await axios.get(targetUrl); // 生产环境建议指定具体域名,不要用* res.set("Access-Control-Allow-Origin", "https://zzzzz.com"); res.send(apiResponse.data); } catch (err) { res.status(err.response?.status || 500).send(err.response?.data || "请求失败"); } }); - 部署Function后,Flutter Web里调用这个Function的URL,而非直接请求Google API,就能绕过前端CORS限制。
3. 检查API密钥的HTTP引用限制
确保你的Google API密钥已配置正确的HTTP引用限制,把你的Firebase Hosting域名(https://zzzzz.com)添加到允许列表中。虽然这不是直接解决CORS,但如果限制配置错误,请求会被Google拒绝,有时会被浏览器误报为CORS错误。
内容的提问来源于stack exchange,提问作者Florian Mac Langlade
相关产品推荐
相关产品推荐

