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

如何解决React Cordova应用Firebase auth/network-request-failed报错

问题解决方案

你当前代码的首要问题是调用createUserWithEmailAndPassword时传入的是DOM元素对象,而非输入框的文本值,该方法要求第二、三位参数为邮箱、密码的字符串类型,非法的参数格式会导致请求构造失败,最终抛出网络错误。
修改后的JS代码如下:

import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";

const signInWithEmail = (setAlertState, setAlertMessage) => {
  const auth = getAuth();
  // 新增.value获取输入框文本值,可额外添加非空判断
  const email = document.getElementById("email-input").value.trim();
  const password = document.getElementById("password-input").value.trim();
  if (!email || !password) {
    setAlertState(true);
    setAlertMessage("邮箱或密码不能为空");
    return;
  }
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => { 
      const user = userCredential.user;
      setAlertState(true);
      setAlertMessage(user.uid);
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      setAlertState(true);
      setAlertMessage(`${errorCode}: ${errorMessage}`);
    });  
}

export default signInWithEmail;

同时按钮组件的type属性建议改为标准的button类型,避免非标准属性带来的未知影响:

<Button
color="primary"
variant="contained"
type="button"
onClick={(event) => {
event.preventDefault();
signInWithEmail(setAlertState, setAlertMessage);
}}
sx={{
position:"relative",
marginTop:"1.5rem",
width:"100%",
height:"3rem",
borderRadius:"1rem",
color:"custom.main",
}}
>
Sign In
</Button>

如果修改后仍报错,请按以下顺序排查Cordova环境配置问题:

  • 检查网络权限配置:在Cordova项目的config.xml中添加安卓网络访问权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 配置域名白名单:安装cordova-plugin-whitelist插件后,在config.xml中添加Firebase相关域名放行规则:
    <allow-navigation href="https://*.firebaseapp.com/*" />
    <allow-navigation href="https://*.googleapis.com/*" />
    <allow-navigation href="https://*.firebaseio.com/*" />
    
  • 检查Webview内容安全策略:在入口HTML的<head>中添加CSP配置,放行Firebase相关请求:
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' https://*.firebaseapp.com https://*.googleapis.com https://*.firebaseio.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
    
  • 确认Firebase初始化正确:检查项目入口处是否已调用initializeApp()传入从Firebase控制台获取的完整配置参数,确保getAuth()能获取到正确的Auth实例。
  • 排查运行环境网络:确认测试用的模拟器/真机可正常访问外网,无代理、防火墙拦截Firebase请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:15:03