React中使用signInWithEmailAndPassword遇Firebase auth/network-request-failed错误求助
解决Firebase auth/network-request-failed登录错误
问题场景
在React中开发用户认证功能,使用Firebase的signInWithEmailAndPassword实现登录逻辑时,触发Firebase: Error (auth/network-request-failed)错误。已尝试禁用CORS、移除提交按钮type="submit"属性、将<Form>改为<div>,均未解决。
前端代码
<Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Control type="email" placeholder="Enter email" onChange={(e) => { setemail(e.target.value) }} /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicPassword"> <Form.Control type="password" placeholder="Password" onChange={(e) => { setpassword(e.target.value) }} /> </Form.Group> <Button variant="primary" onClick={logInWithEmailAndPassword}> Submit </Button> </Form>
登录逻辑代码
const auth = getAuth(); const logInWithEmailAndPassword = async (email, password) => { try { await signInWithEmailAndPassword(auth, email, password); } catch (err) { console.error(err); alert(err.message); } };
可行解决方案
1. 修正函数参数传递错误
当前按钮的onClick直接绑定logInWithEmailAndPassword,会把点击事件对象作为第一个参数传入,而非组件中维护的email和password状态变量。修改点击事件:
<Button variant="primary" onClick={() => logInWithEmailAndPassword(email, password)}> Submit </Button>
同时确保组件已正确声明状态:
const [email, setemail] = useState(''); const [password, setpassword] = useState('');
2. 验证Firebase初始化配置
检查项目中Firebase的初始化代码,确保authDomain、apiKey等参数与Firebase控制台的项目配置完全一致。示例初始化代码:
import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_PROJECT_ID.firebaseapp.com", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_PROJECT_ID.appspot.com", messagingSenderId: "YOUR_SENDER_ID", appId: "YOUR_APP_ID" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app);
authDomain配置错误会导致请求发送到无效域名,直接触发网络错误。
3. 检查Firebase Auth服务状态
登录Firebase控制台,进入Authentication > Sign-in method,确认Email/Password登录方式已启用。若未启用,请求会被Firebase拒绝,表现为网络错误。
4. 排查网络环境问题
- 打开浏览器控制台Network标签,查看具体失败的请求(通常是向
identitytoolkit.googleapis.com发送的请求),确认是否存在超时、4xx/5xx错误。 - 若处于企业网络或代理环境,确认是否允许访问Firebase的Auth服务域名(
identitytoolkit.googleapis.com、firebaseapp.com等)。 - 尝试切换网络(比如手机热点),排除本地网络限制。
内容的提问来源于stack exchange,提问作者Fortuner
相关产品推荐
相关产品推荐

