我正在尝试从火基数据库中获取一些数据。当tring将相同的数据推送到基于js的rest节点时,它不会显示任何数据,但也不会显示错误。当检查邮递员时,它显示200 OK。
[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显示任何数据,这是我的终点。
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
获取以下输出put
[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'
}
发布于 2022-08-07 06:15:32
因为getBlogs
是一个async
函数,所以您的导出是一个Promise
,而不是要发送给调用者的值。
要将实际值发送到响应,可以使用await
或then
app.get("/api/blogs", (req, res) => {
getBlogs.then((blogs) => {
res.json(blogs);
})
});
另外:您的getBlogs
函数没有返回任何值。你的意思是:
async function getBlogs() {
const querySnapshot = await db.collection("myBlogs").get();
return querySnapshot.docs.map((doc) => doc.data());
}
发布于 2022-08-07 08:45:52
按以下方式更新您的路线
app.get("/api/blogs", getBlogs);
并返回调用函数的结果。
async function getBlogs() {
const querySnapshot = await db.collection("myBlogs").get();
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data())
});
return querySnapshot;
}
https://stackoverflow.com/questions/73266968
复制