Angular 无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404)

2024-04-29

我正在使用 Firebase 在 Angular PWA 中执行推送通知,并且我正在点击链接来执行此操作。https://medium.com/@tariqueejaz/progressive-web-app-push-notifications-making-the-web-app-more-native-in-nature-a167af22e004 https://medium.com/@tariqueejaz/progressive-web-app-push-notifications-making-the-web-app-more-native-in-nature-a167af22e004

I am using Angular 6 and have setup the code for everything. when I am trying to run it, then it is showing me a pop up enter image description here.

单击“允许”按钮后,它在控制台上抛出错误:

无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404)。” 代码 : “消息传递/serviceworker 注册失败” 信息 : “消息传递:我们无法注册默认服务工作人员。无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404)。(消息传递/服务工作注册失败)。” 堆 : “FirebaseError:消息传递:我们无法注册默认服务工作人员。无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404)。(消息传递/失败的服务工作人员注册)。↵ athttp://localhost:4200/vendor.js:106604:32 http://localhost:4200/vendor.js:106604:32↵ 在 ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:4200/polyfills.js:2710:26 http://localhost:4200/polyfills.js:2710:26)↵ 在 Object.onInvoke (http://localhost:4200/vendor.js:35701:33 http://localhost:4200/vendor.js:35701:33)↵ 在 ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:4200/polyfills.js:2709:32 http://localhost:4200/polyfills.js:2709:32)↵ 在 Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:4200/polyfills.js:2460:43 http://localhost:4200/polyfills.js:2460:43)↵ 在http://localhost:4200/polyfills.js:3194:34 http://localhost:4200/polyfills.js:3194:34↵ 在 ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31 http://localhost:4200/polyfills.js:2743:31)↵ 在 Object.onInvokeTask (http://localhost:4200/vendor.js:35692:33 http://localhost:4200/vendor.js:35692:33)↵ 在 ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36 http://localhost:4200/polyfills.js:2742:36)↵ 在 Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47 http://localhost:4200/polyfills.js:2510:47)" proto: 错误

My project Structure is: enter image description here

My app and environment folder consists of following files: enter image description here

我的 app.component.ts 文件是

import {Component, OnInit} from '@angular/core';
import * as firebase from 'firebase';
import {AngularFireDatabase, AngularFireList} from 'angularfire2/database';
//import {AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable} from 'angularfire2/database-deprecated';
import {PushService} from './push.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {


  // Declare the variables used
  messaging: any
  token: any  // Stores the current token ID instance generated
  items: AngularFireList<any[]>
  itemsDisplay: AngularFireList<any[]> // List observable for template view (Optional. items itself can be used)
  itemsArr: any[] // Stores the token IDs retrieved from the firebase database 
  hideToken: boolean = false

  // Notificayion object
  pushData: any = {
    'notification': {
      "title": "Background Message Title",
      "body": "Background Message Body"
    },
    "to": ""
  }

  constructor(public db: AngularFireDatabase, private pushService: PushService) {

    // Creates a Firebase List Observable and calls the data in it
    this.itemsDisplay = db.list('/items')

    // Declaring the property value of messaging
    this.messaging = firebase.messaging();

    // Check for token refresh
    this.messaging.onTokenRefresh(function() {
      this.messaging.getToken()
        .then(function(refreshedToken) {
          console.log('Token refreshed.');
        })
        .catch(function(err) {
          console.log('Unable to retrieve refreshed token ', err);
        });
    });
    // Obtaining the firebase data and retrieving token ID values separately
    this.itemsArr = []  // Reinitialize the array to prevent data duplication
    this.items = this.db.list('/items');
    this.items.valueChanges().subscribe(snapshots => {

      console.log(snapshots);
      //snapshots.forEach(snapshot => {
      //  console.log("Hey ,, snapshot......"+snapshot);
      //  this.itemsArr.push(snapshot);
      // });
    });
    // console.log(this.itemsArr)
  }

  // Check for duplicates in token subscription
  checkToken(token, arr) {
    console.log("Inside check token function")
    console.log(arr)
    console.log(token)
    let counter: number = 0
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] === token) {
        counter++
      }
    }
    console.log("Counter value", counter)
    return counter
  }

  // Generate Push through an event
  generatePush() {
    console.log("Inside push function")
    console.log(this.pushData.to)
    if (this.pushData.to === "") {
      console.log("No token available")
      return
    }
    this.pushService.generatePush(this.pushData)
      .subscribe(data => {console.log("Succesfully Posted")}, err => console.log(err))
  }

  // Function to get the data from Firebase Database
  getDataFromFb() {
    this.hideToken = true
  }

  ngOnInit() {
    // Prompt user to grant permission for notifications on loading components
    const self = this
    this.items = this.db.list('/items') 
    this.messaging.requestPermission()
      .then(function() {
        console.log('Notification permission granted.');
        self.messaging.getToken()
          .then(function(currentToken) {
            if (currentToken) {
              self.token = currentToken
              self.pushData.to = self.token
              console.log(self.pushData.to)

              // Set a timeout so as to enable all the data to be loaded
              setTimeout(() => {
                if (self.checkToken(self.token, self.itemsArr) === 0) {
                  console.log("Push occurrence")
                  // self.items.push({tokenID: currentToken})
                } else {
                  console.log("User is already subscribed")
                }
              }, 6500)
              // Displays the current token data
              console.log("currentToken: ", currentToken);
              console.log("Stored token: ", self.token);
            } else {
              // Show permission request.
              console.log('No Instance ID token available. Request permission to generate one.');
            }
          })
          .catch(function(err) {
            console.log('An error occurred while retrieving token.', err);
          });
      })
      .catch(function(err) {
        console.log('Unable to get permission to notify. ', err);
      })

    // Handle incoming messages. Called when:
    // - a message is received while the app has focus
    // - the user clicks on an app notification created by a sevice worker `messaging.setBackgroundMessageHandler` handler.
    this.messaging.onMessage(function(payload) {
      console.log("Message received. ", payload);
    });
  }

}

我的 firebase-messaging-sw.js 文件是:

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

firebase.initializeApp({
  'messagingSenderId': '850143277209' // run it again show me error
});

var messaging = firebase.messaging();
currentMessage = new BehaviorSubject(null);

// Handle Background Notifications

// If you would like to customize notifications that are received in the background (Web app is closed or not in browser focus) then you should implement this optional method
messaging.setBackgroundMessageHandler(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = 'Background Message Title';
  var notificationOptions = {
    body: 'Background Message body.'

  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);




});

我的 Angular.json 文件是:

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "newProjectRoot": "projects",
    "projects": {
        "beautyOfSoul": {
            "root": "",
            "sourceRoot": "src",
            "projectType": "application",
            "prefix": "app",
            "schematics": {
                "@schematics/angular:component": {
                    "styleext": "scss"
                }
            },
            "architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                        "outputPath": "dist/beautyOfSoul",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.app.json",
                        "assets": [
                            "src/favicon.ico",
                            "src/assets",
                            "src/assets/manifest.json",
                            "src/manifest.json",
                            "src/firebase-messaging-sw.js"
                        ],
                        "styles": [
                            "src/styles.scss"
                        ],
                        "scripts": []
                    },
                    "configurations": {
                        "production": {
                            "fileReplacements": {
                                "replace": "src/environments/environment.ts",
                                "with": "src/environments/environment.prod.ts"
                            }],
                            "optimization": true,
                            "outputHashing": "all",
                            "sourceMap": false,
                            "extractCss": true,
                            "namedChunks": false,
                            "aot": true,
                            "extractLicenses": true,
                            "vendorChunk": false,
                            "buildOptimizer": true,
                            "serviceWorker": true
                        }
                    }
                },
                "serve": {
                    "builder": "@angular-devkit/build-angular:dev-server",
                    "options": {
                        "browserTarget": "beautyOfSoul:build"
                    },
                    "configurations": {
                        "production": {
                            "browserTarget": "beautyOfSoul:build:production"
                        }
                    }
                },
                "extract-i18n": {
                    "builder": "@angular-devkit/build-angular:extract-i18n",
                    "options": {
                        "browserTarget": "beautyOfSoul:build"
                    }
                },
                "test": {
                    "builder": "@angular-devkit/build-angular:karma",
                    "options": {
                        "main": "src/test.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.spec.json",
                        "karmaConfig": "src/karma.conf.js",
                        "styles": [
                            "src/styles.scss"
                        ],
                        "scripts": [],
                        "assets": [
                            "src/favicon.ico",
                            "src/assets",
                            "src/manifest.json",
                            "src/firebase-messaging-sw.js"
                        ]
                    }
                },
                "lint": {
                    "builder": "@angular-devkit/build-angular:tslint",
                    "options": {
                        "tsConfig": [
                            "src/tsconfig.app.json",
                            "src/tsconfig.spec.json"
                        ],
                        "exclude": [
                            "**/node_modules/**"
                        ]
                    }
                }
            }
        },
        "beautyOfSoul-e2e": {
            "root": "e2e/",
            "projectType": "application",
            "architect": {
                "e2e": {
                    "builder": "@angular-devkit/build-angular:protractor",
                    "options": {
                        "protractorConfig": "e2e/protractor.conf.js",
                        "devServerTarget": "beautyOfSoul:serve"
                    },
                    "configurations": {
                        "production": {
                            "devServerTarget": "beautyOfSoul:serve:production"
                        }
                    }
                },
                "lint": {
                    "builder": "@angular-devkit/build-angular:tslint",
                    "options": {
                        "tsConfig": "e2e/tsconfig.e2e.json",
                        "exclude": [
                            "**/node_modules/**"
                        ]
                    }
                }
            }
        }
    },
    "defaultProject": "beautyOfSoul"
}

My Network tab is: enter image description here

我的服务人员选项卡是:


我在 React 项目中遇到了类似的问题,对我来说,解决方案是手动将我自己的 js 文件注册为 serviceworker。

navigator.serviceWorker.register('./your-serviceworker-file.js')
.then((registration) => {
  messaging.useServiceWorker(registration);

  // Request permission and get token.....
});

在 firebase 初始化中运行该代码为我解决了这个问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404) 的相关文章

  • Spring RESTful控制器方法改进建议

    我是 Spring REST 和 Hibernate 的新手 也就是说 我尝试组合一个企业级控制器方法 我计划将其用作未来开发的模式 您认为可以通过哪些方法来改进 我确信有很多 RequestMapping value user metho
  • 从脚本内更改自动热键托盘图标

    如何从 Autohotkey 脚本中将托盘图标更改为 my ico 例如 当脚本暂停时 为此 我在托盘菜单中提出了自己的 暂停脚本 菜单项 SingleInstance ignore Menu Tray Tip AutoCase 0 11
  • IE9-11 检测变换样式:preserve-3d

    我为一个项目制作了一个 3d 类型的菜单 自然 IE 会引起问题 因为 IE10 即使 3d 变换工作 也不支持变换样式 preserve 3d 我尝试了解决方法 通过对 3d 菜单容器的每个子元素应用变换 但至少可以说 动画看起来很糟糕
  • 如何制作过期/签名视频嵌入网址

    我是新来的 正在学习网络开发等等 我只知道如何将我的视频嵌入网站中 任何菜鸟都可以轻松获得源代码 他们也可以嵌入它 但在许多网站中 视频 src 均使用重定向器链接进行编码 例如 它会在一段时间后过期 在本例中是一天 我了解到这是一个签名网
  • 使用 QtWebEngine 将 C++ 对象暴露给 Qt 中的 Javascript

    使用 QtWebkit 可以通过以下方式将 C 对象公开给 JavascriptQWebFrame addToJavaScriptWindowObject如中所述https stackoverflow com a 20685002 5959
  • Android Espresso 单击按钮时出现错误

    我正在尝试使用 espresso 框架为 Android 应用程序编写一些 UI 测试 现在我只是检查启动屏幕上是否存在所有元素 然后尝试单击登录按钮 单击按钮时 测试由于错误而失败 我似乎无法理解为什么会发生这种情况 我的测试代码是 Ru
  • Python 中的字符串slugification

    我正在寻找 slugify 字符串的最佳方法 蛞蝓 是什么 https stackoverflow com questions 427102 in django what is a slug 我当前的解决方案基于这个食谱 http code
  • bash:gitolite:找不到命令

    我正在尝试使用 Gitolite 在 Gitlab 中创建一个新分支 我完成安装步骤 当我遇到 设置 gitolite 部分时 我遇到了麻烦 我跟着这个link http sitaramc github com gitolite setup
  • 如何在 kubernetes 中将秘密标记为可选?

    来自文档 除非将秘密标记为可选 否则必须先创建秘密 然后再将其作为环境变量在 pod 中使用 引用不存在的 Secret 将阻止 pod 启动 如何将秘密标记为可选 您正在寻找的是 name ENV NAME valueFrom secre
  • xsi:type 属性搞乱了 C# XML 反序列化

    我使用 XSD exe 根据 XML 架构 xsd 文件 自动生成 C 对象 我正在反序列化 OpenCover 输出 但其中一个部分类未正确生成 这是导致异常的行
  • 一些基本的 PHP 问题 [已关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我只是有一些基本的 php 问题来加深我对学习的理解 但我找不到简单的答案 我有一个 php ajax 应用程序 它生成 mysql
  • View.post(),以及当Runnables被执行时

    我最初的问题是需要知道我的根的高度和宽度View这样我就可以进行程序化的布局更改 就我的目的而言 我不一定需要在onCreate 对于我来说 以编程方式添加我的孩子就足够了View根布局完成后 因此我很乐意使用onWindowFocusCh
  • Azure Functions 计时器触发器线程安全

    我想知道是否有人知道如果您在 Azure 函数上设置了 Cron 设置 如果其任务执行时间超过 5 分钟 则每 5 分钟运行一次 会发生什么情况 它备份吗 或者我应该实现一个锁定功能 以防止某些东西 例如在循环中 处理先前调用已经处理的数据
  • SimpleIoC - 在缓存中找不到类型:Windows.UI.Xaml.Controls.Frame

    第一次由 SimpleIoC 实例化我的 ViewModel 时 我遇到了以下错误 我相信我已经按应有的方式设置了容器 但由于某种原因 我仍然收到以下错误 任何想法或帮助将非常感激 Microsoft Practices ServiceLo
  • R闪亮:使用闪亮的JS从数据表中获取信息

    我想读出所有列名称以及它们在数据表中显示的顺序 由于不同的原因 我无法使用 stateSave 等选项 我对 JS 没有什么把握 但我确信用它可以完成 所以我需要你帮助我 我尝试过类似的代码片段 datatable data callbac
  • PLS-00103:遇到符号“;”当预期出现以下情况之一时:

    我正在尝试插入用户安全问题的答案 以用于密码重置功能 Ellucian 横幅 v8 提供了一个用于运行此 API 的 API 我对他们的 API 非常陌生 从下面的错误消息来看 我还远远没有正确运行它 任何帮助表示赞赏 我尝试在 Oracl
  • Keystore getEntry 在 Android 9 上返回 NULL

    c我已对存储在 Android 密钥库中的登录密码进行了加密和解密 在 Android 9 上 我观察到应用程序在尝试解密密码时崩溃 我无法重现它 但拥有 Pixel 3 的用户是崩溃的设备之一 下面是我如何从密钥库解密密码 private
  • 计算包含字母/数字的行数

    我想要实现的目标很简单 但是解释起来有点困难 我不知道在 postgres 中这是否真的可能 我处于相当基础的水平 SELECT FROM WHERE LEFT JOIN ON HAVING 等等基本的东西 我正在尝试计算包含特定字母 数字
  • Java 和/C++ 在多线程方面的差异

    我读过一些提示 多线程实现很大程度上取决于您正在使用的目标操作系统 操作系统最终提供了多线程能力 比如Linux有POSIX标准实现 而windows32有另一种方式 但我想知道编程语言水平的主要不同 C似乎为同步提供了更多选择 例如互斥锁
  • 如何使用 dql 从数据表中获取唯一值?

    我有一个表 其中有一列存储了各种值 我想使用 dql 从该表中检索唯一值 Doctrine Query create gt select rec school gt from Records rec gt where rec city ci

随机推荐

  • 为什么内联声明不是不完整类型?

    考虑下面的代码 struct Foo struct Bar Foo Bar bar Why isn t Bar an incomplete type struct Bar Full definition struct Bar fails t
  • 在heroku上部署git子目录

    我必须从非主分支部署 git 子目录 我看过这个答案 https stackoverflow com questions 7539382 how can i deploy from a git subdirectory and to Her
  • BackupAgent:“无法恢复包...”

    我已经实现了 BackupAgent 如下所述数据备份 http developer android com guide topics data backup html 注册了一个 API 密钥并在我的 Manifest 中声明了 Back
  • 如何在 AWS Glue 中使用 Spark 包?

    我想使用 DatastaxSpark Cassandra 连接器 https mvnrepository com artifact com datastax spark spark cassandra connector 2 12 2 5
  • 如何让我的精灵向鼠标位置发射一个对象?

    对于一个学校项目 我需要通过实现一种向鼠标位置射击 Kunais Shurikens 的方式来完成下面的 pygame 程序 以便能够击中敌人精灵 import pygame import math import random from p
  • 重新排列关联数组的最优雅的方法是什么?

    假设你有一个关联数组 hash Fruit Apple hash Name Jeff hash Car Ford 并且您无法更改这些变量的创建顺序 因此 Car 总是在 Name 等之后添加到数组中 将 Car 添加 移动到关联数组的开头而
  • 基于 Pandas 中的管道分隔列创建多个新列

    我有一个 pandas 数据框 其中有一个管道分隔的列 其中包含任意数量的元素 称为 零件 这些管道串中的元素数量从 0 到超过 10 个不等 所有管道串中包含的唯一元素的数量并不比行数小很多 这使得我无法在创建新列 对于每一行 我想创建一
  • LINQ 将 Dictionary 转换为 Dictionary

    我今天心情低落 有谁知道一种快速而优雅的方法来转换字典 使键变成值 反之亦然 Example var originalDictionary new Dictionary
  • 按钮上的自定义 Paypal 字段

    当 PayPal 通知我付款时 我需要包含一个自定义字段 我正在尝试使用高级变量 但我没有找到使它们动态化的方法 假设我有一个字段 xyzzy 值为 plugh 我希望 PayPal 包含 form xyzzy plugh 及其发送到我的
  • 如何在 CALayer 中绘制径向渐变?

    I know CAGradientLayer目前不支持径向渐变 只能选择kCAGradientLayerAxial 我想要如下所示的东西 我环顾四周寻找这个问题 发现有一种方法可以解决这个问题 但我并不清楚这些解释 所以我想知道是否可以使用
  • Android 中的音频交叉淡入淡出

    我正在开发一个媒体播放器用于我的学习目的 我希望在媒体播放器应用程序中具有交叉淡入淡出功能 但我不知道从哪里开始 我尝试在互联网上搜索但没有运气 我使用的是安卓MediaPlayer所有媒体播放器相关操作的类 任何人都知道任何解决方法可以实
  • 使用 RSYNC,包含和排除如何组合?

    我想 rsync Volumes B 中的所有内容 除了缓存目录 我想全局排除它 另外 我不想同步任何其他 Volume 我有以下排除文件 Volumes B Cache Volumes 第一行和第三行似乎工作正常 除了 rsync 还拾取
  • 如何使用 DataTables jquery 插件按日期排序?

    我正在使用 datatables jquery 插件并希望按日期排序 我知道他们有一个插件 但我找不到从哪里实际下载它 http datatables net plug ins sorting http datatables net plu
  • NativeActivity未完成

    我从 JavaActivity 调用 NativeActivity 我的 NativeActivity 的入口点是 android main struct android app state 最后 我打电话给 ANativeActivity
  • 处理表单的最佳实践

    我想知道处理表单处理的最佳实践是什么 就我而言 我做了类似的事情 if the user hasn t submited the form 显示表格 else if there are form errors 显示错误 再次显示表格 els
  • 连接表时,rails 在访问连接表中的字段时无论如何都会发出额外的请求

    我有公司表和城市表 公司属于城市 我的数据库架构的一部分是 create table companies force true do t t string title default null false t string address
  • 用顶点之间的渐变填充 matplotlib 多边形

    我正在使用 matplotlib 的 Poly3DCollection 绘制多边形 三角形 的集合 三角形位于具有与其关联的颜色的顶点之间 我目前正在用通过平均三个顶点的颜色确定的纯色填充每个三角形 绘制三角形以形成 3D 表面网格 I w
  • 在snakemake规则中使用pyenv

    我正在使用 Snakemake 来实现一个漫长而复杂的管道 其中涉及一些外部编写的 python2 脚本 当我尝试使用 pyenv 指定 python2 时 pyenv shell命令失败 同时pyenv global and pyenv
  • 如何编译Python 1.0

    出于某种反常的原因 我想尝试Python 1 0 我将如何编译它 或者更确切地说 可以使用当前编译器干净地编译的早期版本是什么 我使用的是 Mac OS X 10 5 不过因为这只是出于好奇 关于语言如何变化 所以在 Linux 虚拟机中编
  • Angular 无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404)

    我正在使用 Firebase 在 Angular PWA 中执行推送通知 并且我正在点击链接来执行此操作 https medium com tariqueejaz progressive web app push notifications