簡體   English   中英

firebase 雲消息傳遞給 A bad HTTP 響應代碼 (404) 單擊“允許”並手動添加服務工作者不起作用

[英]firebase cloud messaging gives A bad HTTP response code (404) after clicking on 'allow' and adding service worker manually doesn't work

我正在開發一個 React 應用程序並嘗試將 FCM 添加到項目中。 首先,我用一個簡單的 index.html 在一個簡單的(非 React)項目上測試了 FCM,一切正常,但現在將它添加到 React 應用程序對我來說有點問題。

所以這里是問題:

我創建了一個簡單的initializeFirebase function 並在應用程序的index.js中調用它。 這是 function:

import firebase from 'firebase';
const firebaseConfig = {
     ... // FCM configs
  };
  
  export const initializeFirebase = () => {

    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
    messaging.requestPermission().then(function() {
       return messaging.getToken();
    }).then(function(token) {
       console.log(token);
    }).catch(function() {
       console.log('Access Denied!');
    });

因此,這預計會詢問用戶許可,然后記錄token 但是在它詢問並單擊允許后,我在控制台上收到此錯誤。 A bad HTTP response code (404) was received when fetching the script. 它進入 catch 塊。

當我搜索時,有人提到手動設置服務工作者,如下所示:

navigator.serviceWorker.register('./firebase-messaging-sw.js')
    .then((registration) => {        
      // Here ask for permission and get the token
    });

但除了A bad HTTP...我還得到Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:8081/') with script ('http://localhost:8081/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script.

我看到有人說 SW 文件沒有被加載或找到。 我在這件事上嘗試了一切。 我首先將文件放在根目錄中,並且它不適用於手動設置 SW。 我把它放在有initializeFirebase的文件旁邊並像'./firebase-messaging-sw.js'一樣傳遞它,仍然沒有變化。 我只是想讓它工作,不管我是手動設置服務工作者還是讓 firebase 自己找到文件都沒有關系。

注意:當我設置: http://localhost:8081/firebase-messaging-sw.jshttp://localhost:8081/src/firebase-messaging/firebase-messaging-sw.js瀏覽器中的http://localhost:8081/src/firebase-messaging/firebase-messaging-sw.js 我不知道這重要與否。

這也是我firebase-messaging-sw.js文件的內容:

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

const firebaseConfig = {
     ... // FCM configs
  };
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload){
  const notif = JSON.parse(payload.data.notification);
  return self.registration.showNotification(notif.title, {...notif});
});

我非常感謝您的幫助

好吧,這是我的一個非常愚蠢的錯誤,正如我所料,這是沒有正確加載 sw 文件的問題。 路徑不對。

如果您在這里處理類似問題,請確保將您的 sw 文件放在公用文件夾中,以便http://localhost:8081/firebase-messaging-sw.js將加載到您的瀏覽器中,然后其他部分就可以了.

我發現本教程對於將 FCM 添加到 React 應用程序的整個過程非常有幫助。 一步一步地做它的說明,你對 go 很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM