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

Expo + React Native中Firebase auth/network-request-failed错误求助

Expo + React Native 中 Firebase auth/network-request-failed 错误排查与修复

问题概述

使用Expo和React Native开发应用时,调用Firebase邮箱注册接口触发auth/network-request-failed错误。已确认安卓模拟器、iOS真机均启用Google服务并登录谷歌账号,尝试更换WiFi、阻止页面重载等操作后问题仍未解决。

相关代码

firebase.js

import { getApp, getApps, initializeApp } from 'firebase/app';
import { initializeAuth, getReactNativePersistence, getAuth } from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';
import AsyncStorage from '@react-native-async-storage/async-storage';

let firebaseApp;

export const getFirebaseApp = () => {
// copy from the firebase config
if (!firebaseApp) {
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};

    firebaseApp = getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();
    initializeAuth(app, { // 变量名错误:应使用firebaseApp而非app
       persistence: getReactNativePersistence(ReactNativeAsyncStorage)
    })

}
return firebaseApp;
};

SignUp.js

import { SafeAreaView, StyleSheet, Text, View,StatusBar as RNStatusBar,Platform, TouchableOpacityComponent, Button, Pressable, Alert } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
import { TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useState } from 'react';
import Checkbox from 'expo-checkbox';
import { getFirebaseApp } from '../firebase';
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth';
import { getFirestore, collection, doc, setDoc } from 'firebase/firestore';


export default Signup = function({navigation} ) {
  const [isPasswordShown, setIsPasswordShown] = useState(false);
  const [isChecked, setIsChecked] = useState(false);
  const navLogin = () => navigation.navigate('Login');
  const firebaseApp = getFirebaseApp();
  const db = getFirestore(firebaseApp);
  const col = collection(db, 'users')
  const [fullName, setFullName] = useState('');
  const [phone, setPhone] = useState('');
  const [userType, setUserType] = useState('Gym');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const registerUser = async (email, password, fullName, phone, userType) => {
    try {
      const userCredential = await createUserWithEmailAndPassword(getAuth(firebaseApp), email, password);
      const user = userCredential.user;
  
      await setDoc(doc(col, user.uid),{
        fullName,
        phone,
        userType
      });
  
      console.log('account created successfully');
      Alert.alert('Success', 'Account created successfully');
      navigation.navigate('Home')
    } catch (error) {
      console.error('account create failed', error.message);
      Alert.alert('Error', 'Account create failed: '+ error.message);
    }
  };
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.signing}>
        {/* Title form */}
        <View style={{marginVertical:22}}>
          <Text style={styles.title}>SignUp</Text>
        </View>

        {/* SignUp form */}
        <View style={styles.filed}>
          {/* Fullname form */}
          <Text style={styles.text}>Full Name</Text>
          <View style={styles.form}>
            <TextInput 
              placeholder='Enter your Name'
              placeholderTextColor={'black'}
              style={{width: '100%'}}
              value={fullName}
              onChangeText={text => setFullName(text)}
            />
          </View>

          {/* Email address form */}
          <Text style={styles.text}>Email address</Text>
          <View style={styles.form}>
            <TextInput 
              placeholder='Enter your Email address'
              placeholderTextColor={'black'}
              keyboardType='email-address'
              style={{width: '100%'}}
              value={email}
              onChangeText={text => setEmail(text)}
            />
          </View>

          {/* password form */}
          <Text style={styles.text}>Password</Text>
          <View style={styles.form}>
            <TextInput 
              placeholder='Enter your Password'
              placeholderTextColor={'black'}
              secureTextEntry={isPasswordShown}
              style={{width: '100%'}}
              value={password}
              onChangeText={text => setPassword(text)}
            />
            <TouchableOpacity
              onPress={() => setIsPasswordShown(!isPasswordShown)}
              style={{position: 'absolute', right:12}}
            >
              {
                isPasswordShown == true ? (
                  <Ionicons name='eye-off' size={24} color={'black'}/>
                ) : (
                  <Ionicons name='eye' size={24} color={'black'}/>
                )
              }
            </TouchableOpacity>
          </View>

          {/* Phone number form */}
          <Text style={styles.text}>Phone number</Text>
          <View style={styles.form}>
            <TextInput 
              placeholder='+61'
              keyboardType='numeric'
              placeholderTextColor={'black'}
              style={{width: '100%'}}
              value={phone}
              onChangeText={text => setPhone(text)}
            />
          </View>

          {/* UserType */}
          <Text style={styles.text}>User Type : {userType}</Text>
        </View>

        {/* agree form */}
        <View style={{ flexDirection: 'row', marginVertical:6}}>
          <Checkbox 
            style={{marginRight: 8}}
            value={isChecked}
            onValueChange={setIsChecked}
            color={isChecked ? 'blue' : undefined}
          />
          <Text> I aggree to the terms and conditions</Text>
        </View>
        <Button 
          title='Sign Up'
          filled
          style={{marginTop: 18, marginBottom: 4}}
          onPress={registerUser} // 参数传递错误:未传入所需的表单值
        />
      </View>
    </SafeAreaView>
  )
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingHorizontal: 20,
  },
  signing: {
    flex: 1,
    justifyContent: 'center',
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
    marginBottom: 30,
  },
  text: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 8,
  },
  form: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 12,
    marginBottom: 20,
    flexDirection: 'row',
    alignItems: 'center',
  },
});

排查与修复步骤

1. 修复Firebase Auth初始化的变量错误

在firebase.js中,initializeAuth调用时使用了未定义的app变量,需替换为已初始化的firebaseApp:

// 修正后代码
initializeAuth(firebaseApp, {
   persistence: getReactNativePersistence(ReactNativeAsyncStorage)
})

该错误会导致Auth模块初始化异常,间接引发网络请求失败。

2. 修复注册按钮的参数传递

SignUp组件中,注册按钮的onPress未传递表单参数,需修改为:

<Button 
  title='Sign Up'
  filled
  style={{marginTop: 18, marginBottom: 4}}
  onPress={() => registerUser(email, password, fullName, phone, userType)}
/>

否则registerUser函数会接收undefined参数,导致Auth请求异常。

3. 验证Firebase配置完整性

确保firebaseConfig中的所有字段(apiKey、authDomain等)均从Firebase控制台正确复制,无遗漏或拼写错误,尤其是authDomain必须与控制台一致。

4. 检查设备网络连通性

  • 确认设备能正常访问Firebase Auth的核心域名(如https://identitytoolkit.googleapis.com),可通过设备浏览器访问验证。
  • 安卓模拟器需确认已连接到可用WiFi,避免因网络隔离导致请求失败。

5. 检查Expo权限配置

  • iOS:确保app.json中配置了网络权限(Expo默认已配置,若有自定义修改需确认):
    "ios": {
      "infoPlist": {
        "NSAppTransportSecurity": {
          "NSAllowsArbitraryLoads": true
        }
      }
    }
    
  • 安卓:app.json中需包含网络权限:
    "android": {
      "permissions": ["INTERNET"]
    }
    

6. 尝试降级Firebase SDK版本

部分新版本Firebase SDK与Expo存在兼容性问题,可尝试降级到稳定版本:

npm install firebase@9.23.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:24:51