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

React Native发送FCM推送通知报错求助:fs模块无法解析

React Native 发送FCM推送通知的可行解决方案

你遇到的核心问题是Firebase Admin SDK和googleapis都是Node.js后端专属库,依赖Node.js核心模块(如fs),无法在React Native环境中运行,而Web版Firebase SDK也不兼容RN。以下是几种可行的解决办法:

1. 搭建后端中转服务(推荐方案)

通过后端服务中转推送请求,是最安全且长期可行的方案——将发送推送的逻辑放在Node.js/Java/Python等后端环境中,React Native前端仅通过API请求触发推送。

示例:Node.js + Express + Firebase Admin SDK

// 后端代码(Node.js)
const express = require('express');
const admin = require('firebase-admin');
const app = express();
app.use(express.json());

// 初始化Firebase Admin(需提前下载服务账号密钥)
const serviceAccount = require('./path-to-service-account-key.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

// 接收RN前端的推送请求接口
app.post('/send-push', async (req, res) => {
  const { targetToken, title, body } = req.body;
  try {
    const message = {
      notification: { title, body },
      token: targetToken
    };
    const response = await admin.messaging().send(message);
    res.status(200).json({ success: true, response });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3000, () => console.log('推送服务运行在端口3000'));

React Native前端调用示例

// RN前端代码
import axios from 'axios'; // 或使用fetch

const triggerPushNotification = async (targetToken, title, body) => {
  try {
    const response = await axios.post('http://你的后端地址/send-push', {
      targetToken,
      title,
      body
    });
    console.log('推送发送成功:', response.data);
  } catch (error) {
    console.error('推送发送失败:', error);
  }
};

2. 使用React Native专用FCM库(前端直接调用)

使用专为RN适配的FCM库,比如@react-native-firebase/messaging,它封装了FCM的原生能力,可直接在RN中发送推送(注意:该方式依赖FCM Legacy HTTP API,官方将在2025年6月停止支持)。

步骤示例:

  1. 安装依赖:
npm install @react-native-firebase/app @react-native-firebase/messaging
# 或使用yarn
yarn add @react-native-firebase/app @react-native-firebase/messaging
  1. 按照官方文档完成Android/iOS的原生配置(添加Google服务配置文件、配置权限等)
  2. 发送推送代码:
import messaging from '@react-native-firebase/messaging';

const sendPush = async (targetToken, title, body) => {
  try {
    const response = await messaging().send({
      token: targetToken,
      notification: { title, body },
    });
    console.log('推送发送成功:', response);
  } catch (error) {
    console.error('推送发送失败:', error);
  }
};

3. 关键注意事项

  • 禁止在RN前端暴露Firebase服务账号密钥或FCM服务器密钥,会导致严重的安全风险,后端中转方案可避免密钥泄露。
  • 如果选择前端直接调用的方式,需留意FCM Legacy API的停用时间,长期项目建议优先采用后端中转方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:13:25