集成Firebase推送通知-React Js Web App

时间:2019-06-24 11:44:03

标签: reactjs firebase push-notification firebase-cloud-messaging google-cloud-messaging

我正在尝试将firebase推送通知集成到我的react js应用中。

我已经按照下面的教程

https://dzone.com/articles/how-to-add-push-notifications-on-firebase-cloud-me

https://github.com/pavelpashkovsky/react-fcm

一切正常,直到Token receiving。 然后我尝试使用curl脚本发送通知,如下所示:

curl -X POST -H "Authorization: key=AAAAAJjqjp4:APA91bFeAaBEuHXFbcDPBgFs4p......END2341BK8HLL0uMum4" -H "Content-Type: application/json" \
   -d '{
  "data": {
    "notification": {
        "title": "FCM Message",
        "body": "This is an FCM Message",
        "icon": "/itwonders-web-logo.png",
    }
  },
  "to": "cG9xo6CkVNs:APA91bEd3ypeXN8P-6dbWQWf0.......NOyIytfm"
}' https://fcm.googleapis.com/fcm/send

但是我没有得到回应

{
    "multicast_id": 6820287658870793009,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
        {
            "error": "AuthenticationError"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

public 文件夹中创建 firebase-messaging-sw.js 文件 并把这段代码

importScripts('https://www.gstatic.com/firebasejs/7.22.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.22.0/firebase-messaging.js')


firebase.initializeApp({
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
})

const initMessaging = firebase.messaging()

在src文件夹中创建 Firebase.js 之后,像这样配置您的Firebase

import firebase from 'firebase/app';
import 'firebase/messaging';

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
};

firebase.initializeApp(firebaseConfig);

export default firebase 

最终,像这样将代码放在 componentDidMount ()内的顶部栏中

import firebase from './Firebase';

 componentDidMount() {
   
    // start push notifications
    const messaging = firebase.messaging()
    messaging.requestPermission().then(() => {
      return messaging.getToken()
    }).then(token => {
      console.log("Firebase Token Get::", token)
    }).catch((err) => {
      console.log("firebase push notification error::", err)
    })
    // end push notifications

}