Firebase Cloud Messaging发送推送通知始终报错,请求排查原因
问题分析与修复方案
核心错误点:
- 变量名不匹配:你定义了推送消息对象为
message,但调用admin.messaging().send()时传入的是未定义的payload,这会直接触发错误。 - 参数名冲突:
.then()回调里的参数用了response,和外部处理HTTP请求的response对象重名。这导致你在回调里调用response.send()时,实际操作的是FCM返回的响应对象(而非要返回给客户端的HTTP响应),FCM的响应对象没有send()方法,调用后会抛出错误,最终进入catch分支。
修正后的代码:
const {onRequest} = require("firebase-functions/v2/https"); const admin = require("firebase-admin"); const serviceAccount = require("./serviceAccountKey.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), }); exports.sendNotification = onRequest((request, response) => { const token = request.params[0].replace("/", ""); const registrationToken = token; console.log("Token: " + token); const message = { notification: { title: "Hello", body: "body text...", }, token: registrationToken, }; // 修正:传入正确的message变量 admin.messaging().send(message) // 修正:将回调参数名改为fcmResponse,避免与外部response冲突 .then((fcmResponse) => { console.log("Successfully sent message:", JSON.stringify(fcmResponse)); response.send(`<h1>Success</h1>`); }) .catch((error) => { const errorString = JSON.stringify(error); console.log("Error sending message:", errorString); response.send(`<h1>Failure: ${errorString}</h1>`); }); });
内容的提问来源于stack exchange,提问作者kerbelda
相关产品推荐
相关产品推荐

