为什么我无法在firebase中以已验证用户身份匿名登录?

hrirmatl  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(179)

我正在尝试以已验证用户身份匿名登录。以下是我的代码:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";

const firebaseConfig = {
  apiKey: "key_here",
  authDomain: "project.firebaseapp.com",
  projectId: "project",
  storageBucket: "project.appspot.com",
  messagingSenderId: "id_here",
  databaseURL: "https://project-default-rtdb.firebaseio.com",
  appId: "app_id_here"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth();

document.getElementById("login").addEventListener("click",function(event){
    event.preventDefault();
    onAuthStateChanged(auth, (user) => {
        if(user){
             //user can successfully login
        }
        else{
            console.log("Something went wrong"); 
        }
    }, (error) => console.error(error)) //Nothing  prints here
}

直到昨天我才能成功登录。但是从今天早上开始,我的控制台里一直出现错误Something went wrong
我没有修改代码,也没有修改我的firebase证书。我哪里错了?

jgovgodb

jgovgodb1#

It was so silly of me to not read the documentation page carefully, I had forgotten to execute the signInAnonymously() method before checking for the user's data, the complete code is as follows:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged, signInAnonymously } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";

const firebaseConfig = {
  apiKey: "key_here",
  authDomain: "project.firebaseapp.com",
  projectId: "project",
  storageBucket: "project.appspot.com",
  messagingSenderId: "id_here",
  databaseURL: "https://project-default-rtdb.firebaseio.com",
  appId: "app_id_here"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth();

document.getElementById("login").addEventListener("click",function(event){
    event.preventDefault();
    signInAnonymously(auth)
        .then(() => {
            onAuthStateChanged(auth, (user) => {
                if(user){
                     //user can successfully login
                }
                else{
                    console.log("Something went wrong");
                }
            });
        })
        .catch((error) => {
             const errorCode = error.code;
             const errorMessage = error.message;
             console.log(errorCode+": "+errorMessage);
         });
});

相关问题