Firebase getToken() TypeError:无法读取属性 [英] Firebase getToken() TypeError: Cannot read property

查看:19
本文介绍了Firebase getToken() TypeError:无法读取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取我网站当前登录用户的令牌.但是,javascript 无法为我获取价值.我认为这里有两个问题:

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:

  1. 当我在开始时获取 Auth.currentUser 时,我收到TypeError:无法读取 null 的属性‘getToken’"的错误.但是当我在控制台中输入 Auth.currentUser.getToken() 时,带有令牌的对象实际上出现了.

  1. When I'm getting Auth.currentUser at start, I get this error of "TypeError: Cannot read property 'getToken' of null". But when I type Auth.currentUser.getToken() in the console, the object with the token actually shows up.

getToken() 返回给我的是一个 promise 对象,其键 'ea' 包含令牌的值.但是当我做 Auth.currentUser.getToken().ea 它让我'空'.如何直接从对象中检索令牌?

What getToken() returns to me is a promise object with its key 'ea' containing the value of the token. but when I do Auth.currentUser.getToken().ea it gets me 'null'. How can I retrieve the token directly from the object?

谢谢!

我检索令牌的代码:

var Auth = firebase.auth()
var token = Auth.currentUser.getToken()

此屏幕截图可能会有所帮助:

This screenshot might be helpful:

推荐答案

根据 firebase.User:getIdToken() 的文档:

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

返回用于向 Firebase 服务标识用户的 JWT 令牌.

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.

该方法返回一个承诺,因为如果令牌已过期,它可能需要往返于 Firebase 服务器:

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))

或者在更经典的 JavaScript 中:

Or in more classic JavaScript:

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

日志输出:

哎……biPA

更新:为确保用户在获取令牌之前已登录,请在 onAuthStateChanged 监听器:

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)
    });
  }
});

这篇关于Firebase getToken() TypeError:无法读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆