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

The script has an unsupported MIME type ('text/html')

我正在尝试为 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')

这是我的摘录 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>

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

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

getIt<FirebaseMessaging>().getToken(vapidKey:"xxx");

我遇到上述错误。

如有任何帮助或指导,我们将不胜感激。

messaging.useServiceWorker(注册); 是解决此问题的唯一方法。

我从 Another Whosebug Question 找到了解决方案,但有评论说 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);
          });
  });

将您的 firebase-messaging-sw.js 放在 index.html 所在的根目录中,并确保 你的``firebase-messaging-sw.js 是空的,它不包含任何代码 这适用于 firestore v9

正如 Firebase 文档所说:

FCM requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client setup process.

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