Cloud Function Firebase,发回值时出错

Cloud Function Firebase, error sending value back

我正在尝试从 firebase 发回简单的值,但出现这样的错误

我的代码是:

exports.getTotalPrice = functions.https.onRequest((req, res) => {
  admin.database().ref('carresult').once('value').then(function(snapshot) {
    var totalPrice = snapshot.val().price;
    res.status(200).send(totalPrice);
  });

});

ps。错误 65000 是我需要它发回的值。

Express documentation for res.send([body])表示:

The body parameter can be a Buffer object, a String, an object, or an Array

在您的数据库中,/carresult/price 可能存储为数字,使 totalPrice 成为 send() 的无效参数。您的选择是将其存储为 String 在传递给 send() 之前将其转换为 String,或者保留一个数字并将其作为对象的 属性 发回: send({price: totalPrice}).

exports.getTotalPrice = functions.https.onRequest((req, res) => {
  admin.database().ref('carresult').once('value').then(function(snapshot) {
    var totalPrice = snapshot.val().price;
    res.status(200).send(String(totalPrice)); // <= ADDED String()
  });
});

另请注意,在 HTTPS 函数中执行数据库读取(异步)是有风险的,正如 Frank van Puffelen 在 中解释的那样:

Note that this is a tricky pattern. The call to the database happens asynchronously and may take some time to complete. While waiting for that, the HTTP function may time out and be terminated by the Google Cloud Functions system...As a general rule I'd recommend using a Firebase Database SDK or its REST API to access the database and not rely on a HTTP function as middleware.