如何使用 Firebase admin 和 Express.js 将后端连接到前端

问题描述 投票:0回答:1

我想将数据从 /api/firestore/read.js 传递到 mainServer.js

它确实有文档,可以打印,但不返回数据。

文件mainServer.js

app.get("/api/profile", async (req, res) => {
  const uid = req.user.uid;
  const userReader = new usersReader(uid);
  const data = await userReader.readData();
  console.log("Data", data); // data is undefined
  res.status(200).send(data);
});

文件read.js

const admin = require("../../firebase-config").admin;
class ReadFireDb {
  constructor(_uid) {
    this.uid = _uid;
  }

  async readData() {
    await admin
      .firestore()
      .collection("users")
      .doc(this.uid)
      .get()
      .then((snapShot) => {
        if (snapShot.exists) {
          console.log(snapShot.data()); // here i print data correctly
          return snapShot.data(); // here is the problem
        } else {
          return null;
        }
      })
      .catch((err) => console.log(err));
  }
}

module.exports = {
  ReadFireDb,
};

返回此数据的正确方法是什么?

javascript node.js firebase express firebase-admin
1个回答
0
投票

这就是答案:`

只需对 read.js 进行一些更改即可

const admin = require("../../firebase-config").admin;
class ReadFireDb {
  data;
  constructor(_uid) {
    this.uid = _uid;
  }

  async readData() {
    await admin
      .firestore()
      .collection("users")
      .doc(this.uid)
      .get()
      .then((snapShot) => {
        if (snapShot.exists) this.data = snapShot.data();
      })

      .catch((err) => console.log(err));
    return this.data;
  }
}

module.exports = {
  ReadFireDb,
};
© www.soinside.com 2019 - 2024. All rights reserved.