React.js中Firebase云函数实现FCM推送遇非空对象错误求助
解决FCM推送错误:Message must be a non-null object
我首次尝试在React.js应用中通过Firebase实时数据库云函数实现FCM推送通知,目前遇到如下错误:
error: Message must be a non-null object
查阅相关解决方案无效,不清楚代码具体问题所在,以下是functions目录下的index.js代码:
const functions = require('firebase-functions'); const admin = require("firebase-admin"); admin.initializeApp(); exports.observeFollow = functions.database .ref('/notifications/{userEmail}/{uid}') .onCreate(async (snapshot, context) => { const userEmail = context.params.userEmail; const uid = context.params.uid; const notificationData = snapshot.val(); console.log("📥 New Notification:", notificationData); console.log('📥 Sender Name:', notificationData.senderName); // 获取被关注用户(应该在/users/{userEmail}路径下) const userRef = admin.database().ref(userEmail); const userSnap = await userRef.once('value'); if (!userSnap.exists()) { console.error('❌ User not found for: ${userEmail}'); return null; } const followedUser = userSnap.val(); const fcmToken = followedUser.fcmToken; console.log('FCMTOKEN------:' + fcmToken); console.log('followedUser Data------:' + followedUser); if (!fcmToken || fcmToken.length < 100) { console.warn('⚠️ Invalid FCM token for user ${userEmail}:', fcmToken); return null; } const payload = { notification: { title: 'You have a new connection!', body: 'Wayne wants to connect.', } }; // const message = { // token: fcmToken, // notification: { // title: "You have a new connection!", // body: 'Wayne wants to connect.'; // } // }; try { const response = await admin.messaging().send(fcmToken, payload); console.log('✅ Message sent:', response); } catch (error) { console.error('❌ Error sending FCM:', error); } return null; });
Firebase函数日志:
错误原因与修复方案
错误根源是调用admin.messaging().send()的方式不符合SDK要求:该方法仅接受单个消息对象作为参数,而非分开传递token和payload。
核心修复步骤:
- 合并token与通知内容为统一的消息对象
- 修正注释代码中的语法错误(body字段末尾多余的分号)
- 替换错误的
send()调用方式
修复后的核心代码片段:
// 正确构建消息对象 const message = { token: fcmToken, notification: { title: 'You have a new connection!', body: `${notificationData.senderName} wants to connect.` // 动态使用发送者名称 } }; try { const response = await admin.messaging().send(message); // 仅传入消息对象 console.log('✅ Message sent:', response); } catch (error) { console.error('❌ Error sending FCM:', error); }
额外需要修复的两个问题:
- 数据库路径错误:原代码中
userRef路径缺少/users前缀,应改为admin.database().ref('/users/' + userEmail),否则无法正确获取用户数据 - 字符串模板语法错误:所有使用
${变量}的地方必须用反引号`包裹字符串,例如:console.error(`❌ User not found for: ${userEmail}`); console.warn(`⚠️ Invalid FCM token for user ${userEmail}:`, fcmToken);
完整修复后的index.js代码:
const functions = require('firebase-functions'); const admin = require("firebase-admin"); admin.initializeApp(); exports.observeFollow = functions.database .ref('/notifications/{userEmail}/{uid}') .onCreate(async (snapshot, context) => { const userEmail = context.params.userEmail; const uid = context.params.uid; const notificationData = snapshot.val(); console.log("📥 New Notification:", notificationData); console.log('📥 Sender Name:', notificationData.senderName); // 获取被关注用户(修正路径:添加/users前缀) const userRef = admin.database().ref(`/users/${userEmail}`); const userSnap = await userRef.once('value'); if (!userSnap.exists()) { console.error(`❌ User not found for: ${userEmail}`); return null; } const followedUser = userSnap.val(); const fcmToken = followedUser.fcmToken; console.log('FCMTOKEN------:' + fcmToken); console.log('followedUser Data------:', followedUser); // 改用逗号避免对象转字符串失真 if (!fcmToken || fcmToken.length < 100) { console.warn(`⚠️ Invalid FCM token for user ${userEmail}:`, fcmToken); return null; } // 正确构建FCM消息对象 const message = { token: fcmToken, notification: { title: 'You have a new connection!', body: `${notificationData.senderName} wants to connect.` } }; try { const response = await admin.messaging().send(message); console.log('✅ Message sent:', response); } catch (error) { console.error('❌ Error sending FCM:', error); } return null; });
内容的提问来源于stack exchange,提问作者Iam Wayne
相关产品推荐
相关产品推荐

