繁体   English   中英

无法获取节点js api中的firebase数据

[英]Unable to fetch the firebase data in the node js api

我正在尝试从 firebase 数据存储中获取一些数据。 当试图将相同的数据推送到基于节点 js 的 rest api 时,它没有显示任何数据但也没有错误。 在检查 postman 时,它显示 200 OK。

  • blog.js [Showing data as expected]
import { db } from "../configAuth/firebase-admin-config.js";

async function getBlogs() {
  const querySnapshot = await db.collection("myBlogs").get();
  querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", doc.data())
  });
}

export default getBlogs = getBlogs();

但是当将getBlogs导入index.js时,它没有通过 http://localhost:5000/api/blogs 显示任何数据,这是我的终点。

  • index.js
import express from "express";
import getBlogs from "./blogs/blog.js";

const app = express();
app.use(express.json());

app.get("/", (req, res) => {
  res.send("API is running...");                //working
});

app.get("/api/blogs", (req, res) => {
  getBlogs.then((blogs) => {                  // not working
    res.json(blogs);
  });
});

const PORT = 5000;
app.listen(PORT, () => console.log(`Server sarted on PORT ${PORT}`));

如果我尝试从 data.json 文件加载数据, index.js能够正确加载该数据,并且我也能够在 http://localhost:5000/api/blogs 中看到数据。 并且能够将数据推送到我们使用本机反应的前端。

获取来自blog.js的以下输出:

[nodemon] starting `node src/index.js`
Server sarted on PORT 5000
YzBuR9QG4xaVzcXU3JyP  =>  {
  blogId: '9087612312390871231',
  createdAt: Timestamp { _seconds: 1659399096, _nanoseconds: 632000000 },
  content: 'content of testing firebase 01',
  createdBy: 'Udayendu Kar',
  published: true,
  updatedAt: 0,
  tags: [ 'firebase', 'development' ],
  title: 'testing firebase'
}
yUsB7V79Vhs9uCQPlhg0  =>  {
  blogId: '9087612312390871232',
  published: 'false',
  createdBy: 'Udayendu Kar',
  tags: [ 'nodejs', 'react' ],
  updatedAt: '0',
  createdAt: Timestamp { _seconds: 1659780527, _nanoseconds: 628000000 },
  title: 'testing node 02',
  content: 'content of testing node 02'
}

由于getBlogsasync function,因此您的导出是Promise而不是您要发送给调用者的值。

要将实际值发送到响应,您可以使用awaitthen

app.get("/api/blogs", (req, res) => {
  getBlogs.then((blogs) => {
    res.json(blogs);
  })
});

更新您的路线如下

app.get("/api/blogs", getBlogs);

并返回调用 function 的结果。

async function getBlogs() {
  const querySnapshot = await db.collection("myBlogs").get();
  querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", doc.data())
  });
  return querySnapshot;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM