【问题标题】:Fetching data from firebase realtime database returns invalid json response从 firebase 实时数据库中获取数据返回无效的 json 响应
【发布时间】:2023-03-12 19:03:01
【问题描述】:

我在这里向 api 发出 fetch 请求 -

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: {},
    };
}

我正在从 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));
};

这给了我这个错误 -

Server Error FetchError: invalid json response body at https://localhost:3000/api/tests/-MUT5-DbK6Ff6CstPSGc reason: Unexpected end of JSON input

除了我在发出 fetch 请求后得到的 json 响应之外,一切似乎都正常工作。我什至无法通过 console.log 查看我实际得到的响应。我错过了什么?

编辑 - 这是我的 firebase 数据库结构,其中测试节点是根节点

【问题讨论】:

  • 在 Postman 中发出请求会得到什么?

标签: javascript reactjs firebase-realtime-database fetch next.js


【解决方案1】:

你的承诺没有回报。这就是 obj 为空的原因。而不是在第一次捕获时发送响应。

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));
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2020-02-27
    • 2019-01-17
    • 1970-01-01
    • 2021-12-06
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多