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

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

问题描述

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

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()返回给我的是一个承诺对象,其键"ea"包含令牌的值.但是当我执行Auth.currentUser.getToken().ea时,它使我为"null".如何直接从对象中检索令牌?

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:

推荐答案

根据

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

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

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.

该方法返回一个promise,因为如果令牌过期,它可能需要往返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)
});

日志输出:

ey ... biPA

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

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

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