Firebase Cloud功能:错误消息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Firebase Cloud功能:错误消息相关的知识,希望对你有一定的参考价值。

我对Node.js和Firebase云功能还不熟悉。我在下面转载了一个我的云功能示例:

exports.sync = functions.https.onRequest((req, res) => {
  admin.database().ref('users').once('value').then(function(snapshot) {
    var updates = {};

    admin.database().ref("Player").child("playerweek12").once('value')
      .then(function(dataSnapshot) {
        var orderedPlayers = dataSnapshot.val();

        snapshot.forEach(function(userSnapshot) {
          var users = userSnapshot.val();
          var selection = users.selection;
          updates[`/users/${userSnapshot.key}/week1`] = 10;
          updates[`/users/${userSnapshot.key}/week2`] = 10;

          admin.database().ref().update(updates).then(function() {
            res.send('it worked');
          });
        });
      });
  });
});

问题是我在Firebase功能日志中不断收到以下错误消息:

Error: Can't set headers after they are sent. 
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11) 
    at ServerResponse.header (/var/tmp/worker/node_modules/express/lib/response.js:767:10) 
    at ServerResponse.send (/var/tmp/worker/node_modules/express/lib/response.js:170:12) 
    at /user_code/index.js:33:16 
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

该函数完全符合我的要求,但错误信息有点奇怪,不是吗?有什么我做错了吗?

答案

您需要在forEach循环之外移动更新块,同时您还没有正确地返回promise:

exports.sync = functions.https.onRequest((req, res) => {
  return Promise.all([admin.database().ref('users').once('value'), admin.database().ref("Player").child("playerweek12").once('value')]).then(results => {
    const users = results[0];
    const player = results[1];
    const updates = {};
    users.forEach(function (userSnapshot) {
      var users = userSnapshot.val();
      var selection = userSnapshot.val().selection;
      updates[`/users/${userSnapshot.key}/week1`] = 10;
      updates[`/users/${userSnapshot.key}/week2`] = 10;
    });
    return admin.database().ref().update(updates).then(function () {
      return res.send('it worked');
    });
  });
});

以上是关于Firebase Cloud功能:错误消息的主要内容,如果未能解决你的问题,请参考以下文章

Firebase Pub Sub Emulator 未收到消息

Firebase Cloud Message (FCM):尝试从 PHP 向设备发送消息(错误:InvalidRegistration)

Flutter Firebase cloud_functions 包抛出错误:内部

Firebase 云功能错误代码和错误消息在 Android 上始终为 Internal

如何在 Firebase Cloud Functions 中确认 PubSub 消息?

将列表添加到Cloud Firebase - Android