如何在ReactJS应用中调用Firebase Cloud Messaging API?
在ReactJS中调用Firebase Cloud Messaging REST API发送通知
核心逻辑
Firebase Admin SDK不能在客户端运行(会暴露私钥引发安全风险),所以只能通过FCM的REST API实现。在React里直接用fetch或axios发送HTTP请求即可,关键是提前准备好两个核心参数:Firebase服务器密钥、目标设备的FCM令牌。
第一步:获取必要参数
- 服务器密钥:登录Firebase控制台 → 进入项目设置 → 切换到「云消息传递」标签 → 复制「服务器密钥」
- 目标设备令牌:React Native端已配置好通知接收,必然已经获取到FCM令牌,你可以把这个令牌存储到Firebase数据库,或者通过接口让ReactJS端获取到。
第二步:ReactJS代码示例
用原生fetch实现
const sendFCMNotification = async () => { const serverKey = '你的Firebase服务器密钥'; const targetToken = 'React Native设备的FCM令牌'; try { const response = await fetch('https://fcm.googleapis.com/fcm/send', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `key=${serverKey}` }, body: JSON.stringify({ to: targetToken, notification: { title: 'Web端通知', body: '这是ReactJS发送的FCM通知' }, data: { // 可选:自定义业务数据 orderId: '12345', type: 'reminder' } }) }); const result = await response.json(); console.log('通知发送成功:', result); } catch (err) { console.error('发送失败:', err); } }; // 需要时调用该函数 // sendFCMNotification();
用axios实现(如果项目已引入axios)
import axios from 'axios'; const sendFCMNotification = async () => { const serverKey = '你的Firebase服务器密钥'; const targetToken = 'React Native设备的FCM令牌'; try { const response = await axios.post('https://fcm.googleapis.com/fcm/send', { to: targetToken, notification: { title: 'Web端通知', body: '这是ReactJS发送的FCM通知' }, data: { orderId: '12345', type: 'reminder' } }, { headers: { 'Content-Type': 'application/json', 'Authorization': `key=${serverKey}` } }); console.log('通知发送成功:', response.data); } catch (err) { console.error('发送失败:', err.response?.data || err.message); } }; // 需要时调用该函数 // sendFCMNotification();
关键注意事项
- 安全红线:绝对不能把服务器密钥硬编码在ReactJS前端代码里!浏览器控制台会直接暴露密钥,导致恶意调用。正确做法是:把发送通知的逻辑封装到你的后端服务(比如Node.js、Python),ReactJS调用自己的后端接口,由后端去调用FCM REST API,服务器密钥只存在后端环境变量中。
- 批量发送:如果要给多个设备发通知,把
to字段换成registration_ids,值为令牌数组,比如registration_ids: [token1, token2, token3] - 自定义通知:可以根据需求调整
notification里的字段,比如添加icon(移动端通知图标)、click_action(点击通知跳转的页面)等。
内容的提问来源于stack exchange,提问作者Dan Tobmson
相关产品推荐
相关产品推荐

