简体   繁体   English

注册时的 ServiceWorker MIME 类型错误 ('text/html') (React)

[英]ServiceWorker MIME Type Error ('text/html') on register (React)

The current behavior:目前的行为:

Service worker does not register due to the below error由于以下错误,Service Worker 未注册

The expected behavior:预期行为:

Service worker registers服务工作者注册


Details细节

Posted as a github issue: https://github.com/facebook/create-react-app/issues/8593作为 github 问题发布: https : //github.com/facebook/create-react-app/issues/8593

Service worker is giving the following error when attempting to register: Service Worker 在尝试注册时出现以下错误:

Error during service worker registration: Service Worker 注册时出错:
DOMException: Failed to register a ServiceWorker for scope (' http://localhost:3000/ ') with script (' http://localhost:3000/sw.js '): DOMException: 无法使用脚本 (' http://localhost:3000/sw.js ') 为范围 (' http://localhost:3000/ ') 注册 ServiceWorker:
The script has an unsupported MIME type ('text/html').该脚本具有不受支持的 MIME 类型 ('text/html')。 console.安慰。 @ index.js:1 @ index.js:1

sw.js is showing in the sources tab of the Chrome dev tools, but not registering. sw.js显示在 Chrome 开发工具的源选项卡中,但未注册。

React version: 16.12.0反应版本:16.12.0

Error Message:错误信息:

Error during service worker registration: DOMException: Service Worker 注册期间出错:DOMException:
Failed to register a ServiceWorker for scope (' http://localhost:3000/ ') with script (' http://localhost:3000/sw.js '):无法使用脚本 (' http://localhost:3000/sw.js ') 为作用域 (' http://localhost:3000/ ') 注册 ServiceWorker:
The script has an unsupported MIME type ('text/html').该脚本具有不受支持的 MIME 类型 ('text/html')。

Failed ServiceWorker in Chrome's Inspect Tab: Chrome 的检查选项卡中的 ServiceWorker 失败: 铬错误


Steps To Reproduce:重现步骤:

Register a Service Worker in React (change from unregister to register, or place SW code directly in index.html, or use a simpler SW. All cause the same error when running, in either dev or a build react app.)在 React 中注册一个 Service Worker(从 unregister 改为 register,或者将 SW 代码直接放在 index.html 中,或者使用更简单的 SW。在运行时都会导致相同的错误,无论是在开发还是构建 react 应用程序中。)

SW Example:软件示例:

export function register() {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker
      .register("./sw.js")
      .then(function(registration) {
        // Successful registration
        console.log(
          "Hooray. Registration successful, scope is:",
          registration.scope
        );
      })
      .catch(function(error) {
        // Failed registration, service worker won’t be installed
        console.log(
          "Whoops. Service worker registration failed, error:",
          error
        );
      });
  }
}

Also, ` http://localhost:3000/sw.js when using the default SW from React returns this HTML:此外,` http://localhost:3000/sw.js在使用 React 的默认 SW 时返回此 HTML:

在此处输入图片说明

Using the code sample above returns index.html (default 404, http://localhost:3000/ ) when trying to access http://localhost:3000/sw.js使用上面的代码示例在尝试访问http://localhost:3000/sw.js时返回 index.html(默认 404, http://localhost:3000/


Suggested fixes:建议修复:

Move sw.js to public folder, gives this error:sw.js移动到 public 文件夹,出现此错误: 公用文件夹错误


Is there a way to change the header (from text/html to application/javascript ) for specifically sw.js when served to the browser in React?当在 React 中提供给浏览器时,有没有办法更改专门用于sw.js的标题(从text/htmlapplication/javascript )?

I tried following some Medium articles on registering custom serviceWorkers in React, to no avail...我尝试了一些关于在 React 中注册自定义 serviceWorkers 的 Medium 文章,但无济于事......

When running webpack dev server, it renders default index.html for missing resource.当运行 webpack 开发服务器时,它会为缺少的资源呈现默认的 index.html。

If you use your browser to load http://localhost:3000/sw.js , you will actually see a rendered react app (started by the index.html).如果您使用浏览器加载http://localhost:3000/sw.js ,您实际上会看到一个渲染的http://localhost:3000/sw.js应用程序(由 index.html 启动)。 That's why the mime type is html, not javascript.这就是为什么 mime 类型是 html,而不是 javascript。

This fallback to index.html is designed to support SPA with front-end routes.这种对 index.html 的回退旨在通过前端路由支持 SPA。 For example /product/123/reviews has no such html file in backend, the JS SPA app takes care of it in front-end.例如/product/123/reviews在后端没有这样的 html 文件,JS SPA 应用程序在前端处理它。

Why your file is missing?为什么你的文件不见了? I guess you created that file in the root folder of your project.我猜您在项目的根文件夹中创建了该文件。

Webpack dev server doesn't serve from that root folder. Webpack 开发服务器不从该根文件夹提供服务。

Move your sw.js into public/ folder of your project, it will be served up as expected.sw.js移动到项目的public/文件夹中,它将按预期提供。

This may be a duplicate of this one 61776698这可能是这个的副本61776698

Main think you need to know: Create the servieWorker inside public folder in order to be treated as .js file and not text/html file.主要认为您需要知道:在公共文件夹中创建 servieWorker 以便将其视为 .js 文件而不是 text/html 文件。

Then register that service in your index.js然后在您的 index.js 中注册该服务

Step 1, create public/sw.js第一步,创建public/sw.js

self.addEventListener('message', async (event) => {
  console.log('Got message in the service worker', event);
});

Step 2, create src/sw-register.js第二步,创建src/sw-register.js

export default function LocalServiceWorkerRegister() {
  const swPath = `${process.env.PUBLIC_URL}/sw-build.js`;
  if ('serviceWorker' in navigator && process.env.NODE_ENV !== 'production') {
    window.addEventListener('load', function () {
      navigator.serviceWorker.register(swPath).then(registration => {
        console.log('Service worker registered');
      });
    });
  }
}

Step 3, in src/index.js , add these two lines第三步,在src/index.js 中,添加这两行

import LocalServiceWorkerRegister from './sw-register';
...
LocalServiceWorkerRegister();

You can change some things for your needs, but with those changes, you should be able to work with a custom service worker in a create-react-app application您可以根据需要更改一些内容,但是通过这些更改,您应该能够在 create-react-app 应用程序中使用自定义服务工作者

You can write code at server side to handle sw.js file.您可以在服务器端编写代码来处理 sw.js 文件。 below is nodejs code which intercept sw.js file request and read from folder and send back to browser.下面是拦截 sw.js 文件请求并从文件夹中读取并发送回浏览器的 nodejs 代码。

app.get('/sw.js', (req, res) => {
  if (__DEVELOPMENT__) {
    http.get('http://localhost:4001/static/build/sw.js', (r) => {
      res.set({
        'Content-Type': 'text/javascript',
        'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate'
      });
      r.setEncoding('utf8');
      r.pipe(res);
    }).on('error', (e) => {
      console.error(`Error in sending sw.js in dev mode : ${e.message}`);
    });
  } else {
    res.setHeader('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate');
    res.sendFile('sw.js', { root: path.join(__ROOT_DIRECTORY__, 'assets', 'build') }); // eslint-disable-line no-undef
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法注册ServiceWorker:脚本具有不受支持的MIME类型('text / html')Vue js? - Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html') Vue js? MSW:无法使用脚本为范围注册 ServiceWorker 该脚本具有不受支持的 MIME 类型('text/html') - MSW: Failed to register a ServiceWorker for scope with script The script has an unsupported MIME type ('text/html') 由于不支持的 MIME 类型 ('text/x-js'),注册 ServiceWorker 失败 - Failed to register ServiceWorker due to unsupported MIME type ('text/x-js') MIME 类型 ('text/html') 错误 - MIME type ('text/html') Error 注册 ServiceWorker 失败:脚本的 MIME 类型不受支持 - reactjs - Failed to register a ServiceWorker: The script has an unsupported MIME type - reactjs ExpressJS 错误:MIME 类型('text/html')不是受支持的样式表 MIME 类型 - ExpressJS error: MIME type ('text/html') is not a supported stylesheet MIME type Flutter 无法使用脚本为 scope 注册 ServiceWorker,该脚本的 MIME 类型不受支持 - Flutter Failed to register a ServiceWorker for scope with script, The script has an unsupported MIME type 不支持MIME类型('text / html') - MIME type ('text/html') is not a supported “php 脚本已加载,即使其 MIME 类型(“text/html”)不是有效的 JavaScript MIME 类型”错误 - “The php script was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type” error 模拟服务器错误 - 脚本具有不受支持的 MIME 类型 ('text/html') - Mock server error - The script has an unsupported MIME type ('text/html')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM