【问题标题】:Firebase function - How to return the object in response as JSON after saving the data to database?Firebase 函数 - 将数据保存到数据库后,如何以 JSON 格式返回对象?
【发布时间】:2018-09-04 04:20:17
【问题描述】:

我正在使用 firebase 函数将数据写入数据库。 我正在使用的功能是由 HTTP 调用触发的(仅限 POST)。 我能够将数据保存到数据库中,但是无法以正确的格式返回数据。 我得到了,以下错误

TypeError: snapshot.val 不是函数

export const saveOrder = functions.https.onRequest(((request, response) => {

    if (request.method == "POST") {

        const data = JSON.stringify(request.body);
        let jsonData = data.replace(/\r?\n\t?/g, '');

        let object = {order: JSON.parse(jsonData), status: "pending"};

        return admin.database()
            .ref("orders")
            .push(object)
            .then(function (snapshot) {
                return response.send(200, snapshot.val());
            });
    } else {
        response.contentType("application/json");
        response.status(400).send('{"message":"Invalid method"}');
        return;
    }
}));

【问题讨论】:

    标签: typescript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    .push() 方法不返回 Snapshot 数据,它返回 Reference

    你可以获得新引用的key:

        .then((reference) => { return response.send(200, reference.key) });
    

    要以正确的格式返回数据,您可以返回传递给 Firebase 的对象:

    return admin.database() ref("orders").push(object)
            .then(function(reference) {
                return response.send(200, {
                      key: reference.key,
                      data: object,
                });
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-24
      • 2011-09-11
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多