![](/img/trans.png)
[英]Angular 2 - Service worker not found - A bad HTTP response code (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.js
或http://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.