javascript - firebase 云消息传递在单击“允许”并手动添加服务工作人员后给出错误的 HTTP 响应代码 (404) 不起作用
问题描述
我正在开发一个 React 应用程序并尝试将 FCM 添加到项目中。首先,我用一个简单的 index.html 在一个简单的(非 React)项目上测试了 FCM,一切正常,但现在将它添加到 React 应用程序对我来说有点问题。
所以这里是问题:
我创建了一个简单的initializeFirebase
函数,并使其在index.js
应用程序中被调用。这是功能:
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
注意:当我设置:或在浏览器中时,不会加载 SW 文件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 应用程序的整个过程非常有帮助。一步一步地做它的指示,你很高兴。
推荐阅读
- r - 使用 `stringr` 删除列名中的异常字符
- java - Maven:无法将资源复制到远程目录
- python - Replace dictionary values with a list
- java - 减少方法中的冗余
- c++ - 停止后恢复完成端口通知
- r - 在 dplyr 中构建动态行数的总和
- linux - java.lang.IllegalArgumentException 错误取决于使用的符号名称 - Clojure
- c++ - Catch2 cmake 函数 'catch_discover_tests()' 在 bulid 时间不起作用
- laravel - 在 laravel 和 vuejs 中处理访问控制的最佳方法是什么?
- dapper - Dapper 如何在不显式打开连接的情况下执行查询?