Firebase getToken() TypeError: Cannot read property

前端 未结 2 742
不知归路
不知归路 2020-12-14 10:23

I\'m trying to get the token of my currently signed in user of my website. However, javascript cannot get the value for me. I think there are 2 problems here:

2条回答
  •  遥遥无期
    2020-12-14 10:57

    According to the documentation of firebase.User:getIdToken():

    Returns a JWT token used to identify the user to a Firebase service.

    Returns the current token if it has not expired, otherwise this will refresh the token and return a new one.

    The method returns a promise, since it may require a round-trip to the Firebase servers in case the token has expired:

    Auth.currentUser.getIdToken().then(data => console.log(data))
    

    Or in more classic JavaScript:

    Auth.currentUser.getIdToken().then(function(data) {
        console.log(data)
    });
    

    Log output:

    ey...biPA

    Update: to ensure that the user is signed in before getting the token, run the above code in an onAuthStateChanged listener:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        user.getIdToken().then(function(data) {
          console.log(data)
        });
      }
    });
    

提交回复
热议问题