[英]Fetching data from firebase realtime database returns invalid json response
Here I am making a fetch request to an api -在这里,我向 api 发出获取请求 -
export async function getServerSideProps(ctx) {
let id = ctx.params.id;
let userObject;
let userId;
const cookie = parseCookies(ctx);
if (cookie.auth) {
userObject = JSON.parse(cookie.auth);
userId = userObject.id;
}
if (!userId) {
return {
redirect: {
permanent: false,
destination: '/',
},
};
}
const res = await fetch(`http://localhost:3000/api/tests/${id}`);
console.log(await res.json());
const data = await res.json();
console.log(data);
// return {
// props: { product: data },
// };
return {
props: {},
};
}
Here I am reading data from firebase realtime database -在这里,我正在从 firebase 实时数据库中读取数据 -
export default async (req, res) => {
const { id } = req.query;
console.log(id);
let obj;
firebase
.database()
.ref('/test/' + id)
.once('value')
.then(snapshot => {
console.log('here');
const data = snapshot.val();
obj = data;
})
.then(() => res.status(200).json(obj))
.catch(err => console.log(err));
};
Which gives me this error -这给了我这个错误 -
Server Error FetchError: invalid json response body at https://localhost:3000/api/tests/-MUT5-DbK6Ff6CstPSGc reason: Unexpected end of JSON input
Everything seems to work except the json response I am getting after making fetch request.除了我在发出获取请求后得到的 json 响应之外,一切似乎都正常工作。 I can't even console.log to see what response I am actually getting.
我什至无法通过 console.log 查看我实际得到的响应。 What am I missing?
我错过了什么?
Edit - Here's my firebase database structure, where test node is root node编辑 - 这是我的 firebase 数据库结构,其中测试节点是根节点
There is no return in your promise.您的 promise 没有退货。 That's why obj is null.
这就是为什么 obj 是 null。 Instead of then just send the response in first capture.
而不是在第一次捕获时发送响应。
export default async (req, res) => {
const { id } = req.query;
console.log(id);
let obj;
firebase
.database()
.ref('/test/' + id)
.once('value')
.then(snapshot => {
console.log('here');
const data = snapshot.val();
obj = data;
res.status(200).json(obj)
})
.catch(err => console.log(err));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.