简体   繁体   中英

Fetching data from firebase realtime database returns invalid json response

Here I am making a fetch request to an 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 -

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. I can't even console.log to see what response I am actually getting. What am I missing?

Edit - Here's my firebase database structure, where test node is root node

在此处输入图像描述

There is no return in your promise. That's why obj is 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));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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