首页 > 解决方案 > 没有从 getIdToken() 获取令牌,但是当我显示文档数据时,它显示 accessToken

问题描述

  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查看数据

标签: node.jsfirebaseexpressgoogle-cloud-firestoregoogle-cloud-functions

解决方案


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,请参阅Cloud Function 文档以及Express 文档。因此,在大多数情况下,您的其余代码不会被执行。


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


推荐阅读