簡體   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