状态 500 "Error: Could not handle the request" 对于每个其他请求



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

状态码:500,正文:"错误:无法处理请求">

这特别奇怪,因为现在,我每次都发送完全相同的消息!也就是说,它是完全相同的API调用,没有头和完全相同的主体。然而,我得到了不同的结果。问题是什么呢?

这是我的云函数:

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!nn" + res);
})
.catch((error) => {
console.log("Error sending message:", error);
response.send("Error sending message:nn" + 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();命令,我有点怀疑…因为在某个时刻,日志告诉我这个函数被调用了两次。

解决方案是把它放在云函数之外,而不是里面!这样的:

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!nn" + res);
})
.catch((error) => {
console.log("Error sending message:", error);
response.send("Error sending message:nn" + error);
});
});

是视频号。

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

这是一个很好的系列!我可以推荐它。

和平!✌️

最新更新