Angular 7注册ServiceWorker失败:获取脚本时收到错误的HTTP响应代码(404)
我得到以下错误Angular 7注册ServiceWorker失败:获取脚本时收到错误的HTTP响应代码(404),angular,service-worker,angular7,angular-service-worker,Angular,Service Worker,Angular7,Angular Service Worker,我得到以下错误 ERROR Error: Uncaught (in promise): TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was receive
ERROR Error: Uncaught (in promise): TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
我使用提示“ng add@angular/pwa”来添加我的ngsw-config.json和清单文件。此提示还将我的“serviceWorker”:true语句和我的register with environment添加到我的app.module.ts中
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
在验证是否正确添加了所有内容后,我运行了命令“ngbuild--prod”,该命令成功地生成了显示的dist
然后我运行了“ng serve--prod”,我收到了图中显示的错误
app.module.ts中使用的行
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
ngsw配置:
{
"index": "/",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
}, {
"name": "icons",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/icons/**"
]
}
}
]
}
在angular.json中放置serviceWorker true:
"configurations": {
"production": {
"serviceWorker": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
由于您提到根目录为dist文件夹,因此在运行
ng build
脚本后,您的service worker.js
文件必须位于dist文件夹中
将“precache”:“sw precache--verbose--config=sw precache config.js”
添加到package.json脚本对象中
然后运行:ng build--prod--aot
,然后npm运行precache
。现在,您的service-worker.js文件将出现在dist文件夹中
由于angular编译器已将您的应用程序代码编译成js文件并存储在dist文件夹中,现在您必须从dist文件夹提供应用程序
但是默认的
ng service
不支持它。我建议您使用http服务器
npm安装http服务器-g
。然后http服务器。/dist-o
。这将在默认浏览器上打开您的应用程序。使用Angular 10,解决方案只是简单地运行http server
,而不是ng serve
,不幸的是,它不支持服务人员
1.使用NPM安装http服务器:
npm安装http服务器--保存开发人员
2.使用http服务器为您的项目提供服务
然后(假设您的项目名为my project),运行:
i、 e.这假设项目的导出位于文件夹dist/myproject/
中(如果不在,则更改)
注意:该
-c-1
指令告诉HTTPServer关闭缓存-。在chrome中检查您的网络日志。是否正确调用url。因为您正在本地尝试,所以您也使用了--prod
标志。生产环境用于此标记谢谢!这解决了问题,但太新了,无法叠加show@AlexMalikov给我错误-->npm运行预缓存>projects@0.0.0precache C:\Users\Admin\Desktop\An7\test app>sw precache--verbose--config=sw-precache-config.js internal/modules/cjs/loader.js:582 throw err;^错误:找不到模块“C:\Users\Admin\Desktop\An7\test app\sw precache config.js”您只需要npm安装--保存开发软件precache网页包插件或npm安装--全局软件precache有一个问题,他看不到这个包。请向我们提供“导出您的项目”是什么意思?@Sofia-您的项目的编译版本网页制作