[英]ServiceWorker MIME Type Error ('text/html') on register (React)
Service worker does not register due to the below error由于以下错误,Service Worker 未注册
Service worker registers服务工作者注册
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 失败:
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
);
});
}
}
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/html
到application/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.