[英]Angular 2 - Service worker not found - A bad HTTP response code (404)
I used sw-precache
to generate a service worker for a Firebase
hosted Angular 2 app. 我使用
sw-precache
为Firebase
托管的Angular 2应用程序生成服务工作者。
Error: 错误:
Service Worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
Structure 结构体
src-
app--
index.html
service-worker.js
sw-precache-config.js
sw-precache-config.js SW-预缓存-config.js
module.exports = {
navigateFallback: '../index.html',
stripPrefix: 'dist',
root: 'dist/',
staticFileGlobs: [
'dist/index.html',
'dist/**.js',
'dist/**.css'
]
};
index.html 的index.html
<script>
if ('serviceWorker' in navigator) {
console.log(navigator.serviceWorker);
navigator.serviceWorker.register('service-worker.js').then(function (registration) {
console.log('Service Worker registered');
}).catch(function (err) {
console.log('Service Worker registration failed: ', err);
});
}
</script>
Your service worker registration code seems fine to me.The problem might be in the project structure.Since you have mentioned the root as dist folder, your service-worker.js file must be in the dist folder after you run the ng build
script. 您的服务工作者注册码对我来说似乎很好。问题可能出在项目结构中。因为您已经提到root作为dist文件夹,所以在运行
ng build
脚本后,您的service-worker.js文件必须位于dist文件夹中。 Add "precache": "sw-precache --verbose --config=sw-precache-config.js"
to your package.json
scripts object.Then run: ng build --prod --aot
,then npm run precache
.Now your service-worker.js file would be present in the dist folder.Since the angular compiler has compiled your app code into js files and stored it in the dist folder ,now you must serve your app from the dist folder.But the default ng serve doesn't support it.I suggest you to use http-server
. 将
"precache": "sw-precache --verbose --config=sw-precache-config.js"
到你的package.json
脚本对象中。然后运行: ng build --prod --aot
,然后npm run precache
。现在您的service-worker.js文件将出现在dist文件夹中。由于角度编译器已将您的应用程序代码编译为js文件并将其存储在dist文件夹中,现在您必须从dist文件夹中提供您的应用程序。但默认ng服务不支持它。我建议你使用http-server
。 npm install http-server -g
.Then http-server ./dist -o
.This open up your app on default browser. npm install http-server -g
。然后http-server ./dist -o
。这会在默认浏览器上打开你的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.