Javascript Service Worker 注册错误:不支持的 MIME 类型 ('text/html')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49566059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:24:16  来源:igfitidea点击:

Service Worker registration error: Unsupported MIME type ('text/html')

javascriptreactjsexpressservice-workercreate-react-app

提问by MattSidor

I'm using create-react-appwith an expressserver.

我正在使用带有快速服务器的create-react-app

create-react-apphas a pre-configured ServiceWorker that caches local assets (https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#making-a-progressive-web-app).

create-react-app有一个预先配置的 ServiceWorker 缓存本地资产(https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#making-a-progressive-web -应用程序)。

The problem I encountered when I tried to publish on my server is that the service-worker.jsfile was available, but I was getting errors in my browser console when it tried to register it.

当我尝试在我的服务器上发布时遇到的问题是该service-worker.js文件可用,但是当我尝试注册它时,我的浏览器控制台中出现错误。

On Firefox, I got this error:

在 Firefox 上,我收到此错误:

Error during service worker registration:

TypeError: ServiceWorker script at https://my-domain.com/service-worker.jsfor scope https://my-domain.com/encountered an error during installation.

Service Worker 注册时出错:

TypeError:位于https://my-domain.com/service-worker.js范围https://my-domain.com/ 的ServiceWorker 脚本在安装过程中遇到错误。

On Chrome, I get the more descriptive error:

在 Chrome 上,我收到了更具描述性的错误:

Error during service worker registration: DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').

Service Worker 注册期间出错:DOMException:无法注册 ServiceWorker:脚本具有不受支持的 MIME 类型 ('text/html')。

Sure enough, if I look in the Network tab of my developer tools and search for the service-worker.jsfile, I can see that it has the wrong MIME type in the HTTP headers.

果然,如果我查看我的开发人员工具的网络选项卡并搜索该service-worker.js文件,我可以看到它在 HTTP 标头中具有错误的 MIME 类型。

I could not understand, though, why it has the wrong MIME type?

但是,我不明白为什么它的 MIME 类型错误?

采纳答案by MattSidor

In my Express server application, I have one wildcard (asterisk / *) route that redirects to index.html:

在我的 Express 服务器应用程序中,我有一个通配符(星号 /*)路由重定向到index.html

// Load React App
// Serve HTML file for production
if (env.name === "production") {
  app.get("*", function response(req, res) {
    res.sendFile(path.join(__dirname, "public", "index.html"));
  });
}

This is a very common design pattern. However, it means that any requests for unknown text files initially get redirected to index.html, and therefore return with the MIME type of "text/html", even if it's actually a JavaScript or SVG or some other kind of plaintext file.

这是一种非常常见的设计模式。但是,这意味着对未知文本文件的任何请求最初都会被重定向到index.html,因此会返回 MIME 类型"text/html",即使它实际上是 JavaScript 或 SVG 或某种其他类型的纯文本文件。

The solution I found was to add a specific route for service-worker.jsbeforethe wildcard route:

我找到的解决方案是在通配符路由service-worker.js之前添加特定路由:

app.get("/service-worker.js", (req, res) => {
  res.sendFile(path.resolve(__dirname, "public", "service-worker.js"));
});
app.get("*", function response(req, res) {
  res.sendFile(path.join(__dirname, "public", "index.html"));
});

Now, when the browser looks for service-worker.js, Express will return it with the correct MIME type.

现在,当浏览器查找 时service-worker.js,Express 将返回正确的 MIME 类型。

(Note that if you try adding the service-worker.jsroute after the wildcard, it won't work because the wildcard route will override.)

(请注意,如果您尝试service-worker.js在通配符后添加路由,它将不起作用,因为通配符路由将被覆盖。)

回答by WapShivam

ServiceWorker supported MIME type are 'text/javascript', application/javascript and application/x-javascript. go to your server file and set

ServiceWorker 支持的 MIME 类型是“text/javascript”、application/javascript 和 application/x-javascript。转到您的服务器文件并设置

    response.writeHead(201, {
        'Content-Type': 'application/javascript'
    });

回答by Mir-Ismaili

Replacing

更换

'/service-worker.js'

with

'./service-worker.js'

(in navigator.serviceWorker.register('/service-worker.js'))

(在navigator.serviceWorker.register('/service-worker.js'))

solved my similar issue.

解决了我的类似问题。

回答by Stamatis Rapanakis

Make sure that the service worker file is generated (Chrome DevTools -> Sources -> Filesystem). You may receive such an error if the service worker file is not generated at all (check your deployment script).

确保生成了 service worker 文件(Chrome DevTools -> Sources -> Filesystem)。如果根本没有生成 Service Worker 文件,您可能会收到这样的错误(检查您的部署脚本)。

回答by Hoang Duong

In case, you're working on with NodeJS, serviceWorker file should place at public folder. If you're using Webpack to export serviceWorker to public, you need to use 'copy-webpack-plugin'.

如果你正在使用 NodeJS,serviceWorker 文件应该放在 public 文件夹中。如果您使用 Webpack 将 serviceWorker 导出到公共,则需要使用“copy-webpack-plugin”。

回答by zemil

I use nginx to serve react app and I resolved this issue adding mime types to nginx:

我使用 nginx 来提供 react 应用程序,并解决了向 nginx 添加 mime 类型的这个问题:

http {
    include    mime.types; // <--- this line

    # another config details
}

Also you can find mime.types file here

你也可以在这里找到mime.types 文件

回答by Oscar Barrios

React: public/index.html

反应:public/index.html

<script> 
  if ('serviceWorker' in navigator) {
    window.addEventListener('sw-cached-site.js', function() {
      navigator.serviceWorker.register('service-worker.js', {
        scope: '/',
      });
    });
  } 
  window.process = { env: { NODE_ENV: 'production' } };
</script>

Note: Full app/site public/sw-cached-site.js

注意:完整的应用程序/站点 public/sw-cached-site.js

const cacheName = 'v1';
self.addEventListener('activate', (e) =>{
  e.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if(cache !== cacheName) { 
            return caches.delete(cache);
          }
        })
      )
    })
  )
});
self.addEventListener('fetch', e => { 
  e.respondWith(
      fetch(e.request)
        .then(res => {
            const resClone = res.clone();
            caches
                .open(cacheName)
                .then(cache => {
                    cache.put(e.request, resClone);
                }); 
                return res;
        }).catch(err => caches.match(e.request).then(res => res))
  );
});

回答by Qais Khateeb

I was facing the same issue and removing other firebase libraries from my config solve the issue for me Check this on Github

我遇到了同样的问题,从我的配置中删除其他 firebase 库为我解决了这个问题在 Github 上检查


// Change this 
var firebaseConfig = {
    apiKey: "*********",
    authDomain: "**********",
    databaseURL: "*********",
    projectId: "***********",
    storageBucket: "************",
    messagingSenderId: "***********",
    appId: "************"
};

// To =>
var firebaseConfig = {
  apiKey: "*****************",
  projectId: "**********",
  messagingSenderId: "*******",
  appId: "***********"
};

回答by Ali The Flying Tiger

The script has an unsupported MIME type ('text/html'). Failed to load resource: net::ERR_INSECURE_RESPONSE (index):1 Uncaught (in promise) DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').

该脚本具有不受支持的 MIME 类型 ('text/html')。无法加载资源:net::ERR_INSECURE_RESPONSE (index):1 Uncaught (in promise) DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html')。

Code for template.js root file

template.js 根文件的代码

export default ({ markup, css }) => {
  return `<!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>MERN Marketplace</title>
          <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400">
          <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

          <style>
              a{
                text-decoration: none
              }
          </style>
          <link rel="manifest" href="./manifest.json">
        </head>
        <body style="margin:0">
            <div id="root">${markup}</div>
          <style id="jss-server-side">${css}</style>
          <script type="text/javascript" src="/dist/bundle.js"></script>
          <script>
          if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js').then(function() { 
              console.log("Service Worker Registered"); 
            });
          }
          </script>
        </body>
      </html>`;
};