React Native Expo调用Firebase云函数报错:无法连接服务器
React Native Firebase云函数调用异常:httpsCallable无法连接服务器,httpsCallableFromUrl正常
环境依赖
"@react-native-firebase/firestore": "^23.1.1""@react-native-firebase/functions": "23.1.1""@react-native-firebase/app": "^23.1.1"
客户端代码与错误信息
调用部署的云函数时抛出错误:{"error": [Error: Could not connect to the server.]}
客户端调用代码:
import { httpsCallable, getFunctions } from '@react-native-firebase/functions'; const functions = getFunctions(); const checkAuth = httpsCallable(functions, 'checkAuth'); // 按钮点击事件中的调用逻辑 onPress: async () => { try { const result = await checkAuth(); console.log({ result: result.data }); Alert.alert( 'Success', `Operation successful! Fetched ${(result?.data as []).length} products.`, ); } catch (error) { console.log({ error }); Alert.alert('error', 'check error'); } }
配置说明:使用Android的google-services.json和iOS的GoogleService-Info.plist自动完成Firebase初始化,无需手动调用initializeApp()。
云函数配置与代码
云函数已成功部署在Firebase控制台的us-central1默认区域,代码如下:
import { setGlobalOptions } from 'firebase-functions'; import { onCall } from 'firebase-functions/v2/https'; import * as logger from 'firebase-functions/logger'; import { initializeApp } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore'; setGlobalOptions({ maxInstances: 10 }); initializeApp(); exports.checkAuth = onCall(async (request) => { logger.info(request?.auth?.token); logger.info(request?.auth?.uid); return { auth: request.auth, }; });
已知有效替代方案
使用httpsCallableFromUrl()传入完整云函数URL可正常调用,示例代码:
const functions = getFunctions(); const checkAuth = httpsCallableFromUrl(functions, 'https://us-central1-<你的项目ID>.cloudfunctions.net/checkAuth');
问题解决建议
显式指定云函数区域
尽管默认区域是us-central1,但显式指定区域可避免自动解析错误,修改客户端代码:import { httpsCallable, getFunctions } from '@react-native-firebase/functions'; // 显式指定区域为us-central1 const functions = getFunctions(null, 'us-central1'); const checkAuth = httpsCallable(functions, 'checkAuth');验证配置文件有效性
确认google-services.json(Android)和GoogleService-Info.plist(iOS)中的项目信息与Firebase控制台完全一致,且文件放置路径正确:- Android:放置在
android/app/目录下 - iOS:添加到Xcode项目目标的资源文件中
- Android:放置在
检查网络访问限制
确保测试设备可以正常访问*.cloudfunctions.net域名,排除代理、防火墙或网络环境导致的连接问题。检查云函数状态
登录Firebase控制台,确认checkAuth函数处于已部署状态,查看函数日志是否有异常报错。
内容的提问来源于stack exchange,提问作者Roy Lee
相关产品推荐
相关产品推荐

