Status 500 "Error: Could not handle the request" for every other request

Status 500 "Error: Could not handle the request" for every other request

我做了一个 Flutter 应用程序,刚开始使用 Cloud Functions 向其他手机发送推送通知。我通过调用 API 调用 Cloud Function 来使其工作,也就是说,消息已发送并且我收到响应代码 200。但有趣的是,大约每隔一段时间(有时更多,有时更少) ) 我得到回复:

Status code: 500, body: "Error: Could not handle the request"

这特别奇怪,因为此刻,我每次都发送完全相同的消息!...因为,它是完全相同的 API 调用,没有 header 和完全相同 body。然而,我得到了不同的结果。可能是什么问题?

这是我的云函数:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports.sendMsg = functions.https.onRequest((request, response) => {

  var decodedBody = JSON.parse(request.body);
  const message = decodedBody;

  // Send a message to the device corresponding to the provided
  // registration token:
  admin.initializeApp();
  admin.messaging().send(message)
      .then((res) => {
        // Response is a message ID string.
        console.log("Successfully sent message:", res);
        response.send("Message sent!\n\n" + res);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
        response.send("Error sending message:\n\n" + error);
      });
});

这是我的 API 电话:

import 'dart:convert';
import 'my_firebase.dart';
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';

//...//
void msgFunction(){
  final FirebaseMessaging _fcm = FirebaseMessaging();
         await MyFirebase.myFutureFirebaseApp;
          String fcmToken = await _fcm.getToken();
          http.Response res;

          try {
            res = await http.post(
              'https://us-central1-<my_project>.cloudfunctions.net/sendMsg',
              body: jsonEncode({
                "notification": {
                  "title": "This is my title",
                  "body": "Accept Ride Request",
                },
                "data": {
                  "score": "850",
                  "time": "245",
                  "click_action": "FLUTTER_NOTIFICATION_CLICK",
                  "id": "1",
                  "status": "done",
                },
                "token": "$fcmToken",
              }
              ),
            );
          } catch (e) {
            print('Caught an error in API call!');
            print('e is: ${e.toString()}');
            if (res != null) print('Status code in apiCall() catch is ${res.statusCode}');
          }
}

执行失败的在线函数日志:

Function execution started
Function execution took 173 ms, finished with status: 'crash'

我自己解决了!

问题显然是 admin.initializeApp(); 命令,我有点怀疑...因为在某些时候,日志告诉我这个函数被调用了两次。

解决方案是将它放在 Cloud Function 之外,而不是放在里面!像这样:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.sendMsg = functions.https.onRequest((request, response) => {

  var decodedBody = JSON.parse(request.body);
  const message = decodedBody;

  // Send a message to the device corresponding to the provided
  // registration token:
  admin.messaging().send(message)
      .then((res) => {
        // Response is a message ID string.
        console.log("Successfully sent message:", res);
        response.send("Message sent!\n\n" + res);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
        response.send("Error sending message:\n\n" + error);
      });
});

这是视频号。 Firebase 的 Cloud Functions 视频系列教程中的第 2 个让我明白了:

https://firebase.google.com/docs/functions/video-series

这个系列不错!我可以推荐它。

和平! ✌️