【问题标题】:not getting a token from getIdToken() but when i display document data it shows accessToken没有从 getIdToken() 获取令牌,但是当我显示文档数据时,它显示 accessToken
【发布时间】:2020-05-20 15:22:22
【问题描述】:
  const user = {
    email: req.body.email,
    password: req.body.password,
  };
  let errors = {};
  if (isEmpty(user.email)) {
    errors.email = "Must not be empty";
  }
  if (isEmpty(user.password)) {
    errors.password = "Must not be empty";
  }

  if (Object.keys(errors).length > 0) {
    return res.status(400).json(errors);
  }

  firebase
    .auth()
    .signInWithEmailAndPassword(user.email, user.password)
    .then((data) => {
      return data;
    })

//Problem this is working and showing json objecct with token
//    .then((data) => {
//      return res.status(201).json(data);
//    })
//If i fetch token in place of whole json object is show empty while
//the tutorial i am following gets token like this
.then((data) => {
      return res.status(201).json({token:data.user.getIdToken()});
    })

    .catch((err) => {
      if (err.code === "auth/user-not-found") {
        return res.status(403).json({ message: "User not registered" });
      } else if (err.code === "auth/wrong-password") {
        return res
          .status(403)
          .json({ message: "email and password doesnot match" });
      } else return res.status(500).json({ error: err.code });
    });
});

请帮助我,此文档数据具有 uid,如果您进行控制台操作,它将显示令牌,但我无法使用 getIdToken 从中访问 idToken,这就是为什么如果有人可以提供帮助,我的代码会出错 访问邮箱是momin@gmail.com 密码是123456 可以调用api查看数据

【问题讨论】:

  • 请解释您希望代码做什么。这里有很多我们看不到的变量,所以很难说应该发生什么。我建议使用用户的 UID 来创建每个用户的文档,而不是他们为自己选择的名称。
  • 我需要代码来创建一个身份验证用户,然后我需要从身份验证用户那里获取 uid 并在 db 中创建一个文档
  • 是的,我明白了。由于您的代码中有很多变量,因此无法想象您是如何调用此代码的,以及您期望的结果究竟是什么。您显示的代码也不完整。我建议添加一些日志语句来验证每个阶段是否按预期工作,并且每个变量都包含您预期的值。
  • 它将数据添加到数据库是我在 userCredentials 中没有 userId 字段我不知道也许我无法从身份验证用户那里获取 uid 我需要帮助

标签: node.js firebase express google-cloud-firestore google-cloud-functions


【解决方案1】:

firebase.auth().createUserWithEmailAndPassword()JavaScript SDK 的方法,而不是Admin SDK 的方法。

在云函数中,您必须使用 Admin SDK,尤其是 Admin SDK 的 createUser() 方法。

另外,请注意这样做

  db.collection("users")
    .doc(newUser.userHandle)
    .get()
    .then((doc) => {
       //....
    })
    .then((data) => {
      userId = data.user.uid;
      return res.json({ data: data.user.getIdToken() });
    })

您可能正在终止您的 HTTP 云函数,请参阅 Cloud Function docExpress doc。因此,在大多数情况下,您的其余代码不会被执行。


我建议您观看 Doug 介绍的三个有关“JavaScript Promises”的 Firebase 视频:https://firebase.google.com/docs/functions/video-series/

【讨论】:

  • 如果我不写 data.user.getIdToken() 其余代码的工作原理就像我没有从 firebase 获得承诺令牌一样 getIdToken() 仅返回 {} 如果我删除了代码的工作原理
  • 如果您修改了代码,请编辑您的问题并添加新代码。
猜你喜欢
  • 2022-11-19
  • 2020-11-05
  • 2014-05-13
  • 2022-01-02
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2018-01-07
  • 2021-03-11
相关资源
最近更新 更多