You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Cloud Messaging报错:admin.messaging()不是函数,求解决方案

解决Firebase Cloud Messaging报错:TypeError: admin.messaging is not a function

问题场景

使用firebase-admin v5.13.1调用Firebase Cloud Messaging发送通知时,出现错误:TypeError: admin.messaging is not a function。

配置文件代码

var admin = require("firebase-admin");

var serviceAccount = require("./google-services.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

module.exports.admin = admin

API文件代码

const admin = require('../firebaseConfig')

async function sendFireBaseNotification(registrationToken , message  ){

  const options =  notification_options

  return admin.messaging().sendToDevice(registrationToken, message, options)
  .then( response => {

    console.log("Notification sent successfully"+response)
    
  })
  .catch( error => {
      console.log(error);
  });
}

解决方案

1. 修复API文件的导入错误

配置文件中导出的是包含admin属性的对象,而非直接导出admin实例。API文件中需要解构获取正确的admin实例:

// 替换原来的导入方式
const { admin } = require('../firebaseConfig')

2. 显式加载Messaging模块(v5.x版本兼容)

对于firebase-admin v5.x版本,可能需要显式加载messaging模块才能使用admin.messaging(),修改配置文件:

var admin = require("firebase-admin");
require("firebase-admin/messaging"); // 新增:显式加载messaging模块

var serviceAccount = require("./google-services.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

module.exports.admin = admin

3. 补全未定义的notification_options

API文件中notification_options未定义,需要添加有效的配置对象,示例:

async function sendFireBaseNotification(registrationToken , message  ){
  // 新增:定义notification_options
  const notification_options = {
    priority: "high",
    timeToLive: 60 * 60 * 24 // 1天有效期
  };

  return admin.messaging().sendToDevice(registrationToken, message, notification_options)
  .then( response => {
    console.log("Notification sent successfully", response)
  })
  .catch( error => {
      console.log(error);
  });
}

内容的提问来源于stack exchange,提问作者unknown Gabbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:50:29