使用firebase-admin@11.3.0时admin.messaging()不是函数的问题求助
解决Firebase Cloud Functions中
admin.messaging is not a function错误 问题场景
尝试向主题"All"发送通知时,控制台抛出错误:
Notification sent failed: TypeError: admin.messaging is not a function
原代码
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers. const functions = require('firebase-functions'); // The Firebase Admin SDK to access Firestore. var admin = require("firebase-admin/app"); const { applicationDefault } = require('firebase-admin/app'); admin.initializeApp({ credential: applicationDefault(), databaseURL: "my-firebase-url" }); exports.notificationsOnCreate = functions.database.ref("/{type}/{id}/").onCreate(async (snapshot, context) => { const payload = { notification: { title: 'cloud function demo', body: 'this is a test notification' } }; try{ return await admin.messaging().sendToTopic("All", payload) .then(function(response){ console.log('Notification sent successfully: ', response); }); } catch(err) { console.log('Notification sent failed: ', (err)); } })
版本说明
已确认firebase-admin版本为^11.3.0,排除版本过低的问题(相关帖子建议升级到5.1以上)。
package.json内容
{ "name": "functions", "description": "Cloud Functions for Firebase", "scripts": { "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "16" }, "main": "index.js", "dependencies": { "firebase-admin": "^11.3.0", "firebase-functions": "^4.1.0" }, "devDependencies": { "firebase-functions-test": "^0.2.0" }, "private": true }
问题原因与解决方案
Firebase Admin SDK v10+采用模块化导入方式,原代码仅导入了firebase-admin/app模块,未单独导入messaging功能模块,导致无法调用admin.messaging()。
修正步骤:
- 调整Admin SDK的导入方式,同时导入
initializeApp和getMessaging - 使用
getMessaging()获取messaging实例,而非通过admin.messaging()调用
修正后的代码:
const functions = require('firebase-functions'); const { initializeApp, applicationDefault } = require('firebase-admin/app'); const { getMessaging } = require('firebase-admin/messaging'); initializeApp({ credential: applicationDefault(), databaseURL: "my-firebase-url" }); const messaging = getMessaging(); exports.notificationsOnCreate = functions.database.ref("/{type}/{id}/").onCreate(async (snapshot, context) => { const payload = { notification: { title: 'cloud function demo', body: 'this is a test notification' } }; try { const response = await messaging.sendToTopic("All", payload); console.log('Notification sent successfully: ', response); return response; } catch(err) { console.log('Notification sent failed: ', err); throw err; } })
额外优化:原代码中await和.then()混用,修正后统一使用async/await写法,代码更简洁易读。
内容的提问来源于stack exchange,提问作者Bountx
相关产品推荐
相关产品推荐

