该脚本具有不受支持的 MIME 类型(“text/html”)

Idu*_*ool 11 flutter firebase-cloud-messaging flutter-web

我正在尝试为Flutter Web 平台设置 Firebase Push 。

我复制了与各种教程中所示相同的设置并遇到以下错误,

Uncaught (in promise) Error: [firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:61027/firebase-cloud-messaging-push-scope') with script ('http://localhost:61027/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html')
Run Code Online (Sandbox Code Playgroud)

这是我的 Index.html 的摘录

<script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('flutter-first-frame', function () {
        navigator.serviceWorker.register('/flutter_service_worker.js')
        .then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    })
      });
 }
</script>
<script src="main.dart.js" type="application/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

Index.html 和 flutter_service_worker.js 位于同一文件夹中。

我收到一条服务注册成功的消息。收到推送权限后,我使用以下代码来获取令牌,然后出现错误。

getIt<FirebaseMessaging>().getToken(vapidKey:"xxx");
Run Code Online (Sandbox Code Playgroud)

我收到上述错误。

任何帮助或指导将不胜感激。

Giu*_*zio 7

正如 Firebase 文档所述:

FCM 需要 firebase-messaging-sw.js 文件。除非您已经有 firebase-messaging-sw.js 文件,否则请在检索令牌之前创建一个具有该名称的空文件并将其放置在域的根目录中。您可以稍后在客户端设置过程中向文件添加有意义的内容。

所以基本上你需要在反应公共文件夹中创建一个空的“firebase-messaging-sw.js”文件,它应该按预期工作

在此输入图像描述


Idu*_*ool 1

消息传递.useServiceWorker(注册);是解决此问题的唯一方法。

我从另一个 Stackoverflow 问题中找到了解决方案,但有评论说useServiceWorker已被弃用,这就是我不倾向于使用它的原因,但我目前没有看到任何其他选项在起作用。这是我的完整注册片段。

const messaging = firebase.messaging();
navigator.serviceWorker.register('/firebase-message-sw.js')
          .then(function (registration) {
            // Registration was successful
            console.log('firebase-message-sw :ServiceWorker registration successful with scope: ', registration.scope);
            messaging.useServiceWorker(registration);
          }, function (err) {
            // registration failed :(
            console.log('firebase-message-sw: ServiceWorker registration failed: ', err);
          });
  });
Run Code Online (Sandbox Code Playgroud)