[英]sw-toolbox script evaluation failed
I'm fiddling around with service workers and want to use sw-toolbox which has a way to support express-style routing. 我在摆弄服务人员,并想使用sw-toolbox,它具有一种支持快速样式路由的方法。 However, when I import it with any version of these lines:
但是,当我导入这些行的任何版本时:
importScripts('node_modules/sw-toolbox/sw-toolbox.js');
importScripts('../node_modules/sw-toolbox/sw-toolbox.js');
importScripts('/node_modules/sw-toolbox/sw-toolbox.js');
I get the following error: 我收到以下错误:
A bad HTTP response code (404) was received when fetching the script.
:3000/node_modules/sw-toolbox/sw-toolbox.js Failed to load resource: net::ERR_INVALID_RESPONSE
Here's my service worker code so far: 到目前为止,这是我的服务人员代码:
(global => {
'use strict';
//Load the sw-toolbox library
importScripts('node_modules/sw-toolbox/sw-toolbox.js');
//Ensure that our service worker takes control of the page asap
global.addEventListener('install', event => event.waitUntil(global.skipWaiting()));
global.addEventListener('activate', event => event.waitUntil(global.clients.claim()));
})(self);
What am I doing wrong? 我究竟做错了什么?
I'm not sure if this is right, as I didn't find any reference to this in the tutorials on sw-toolbox online, but I found a workaround to get it to import. 我不确定这是否正确,因为在在线sw-toolbox的教程中没有找到对此的任何引用,但是我找到了一种解决方法来将其导入。
Apparently service workers don't work like module.import, that is, relative to the calling code directory. 显然,服务工作者并不像module.import那样工作,也就是说,相对于调用代码目录而言。 So I added this script in my server:
因此,我在服务器中添加了此脚本:
//serve the sw-toolbox
server.get('/sw-toolbox.js', (req, res) => {
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('content-type', 'text/javascript');
let file = path.join(__dirname, 'node_modules', 'sw-toolbox', 'sw-toolbox.js');
res.sendFile(file);
});
And call it from the service worker thusly: 然后从服务人员处调用它:
importScripts('/sw-toolbox.js');
Can anyone explain to me why this works and importScripts doesn't? 谁能向我解释为什么这样做有效,而importScripts不起作用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.