【问题标题】:404 Not found while instantiating web worker in backbone.jsI404 在backbone.jsI 中实例化Web Worker 时未找到
【发布时间】:2019-05-23 07:13:05
【问题描述】:

我试图在一个backbone.js 项目中实现web worker,我收到了错误消息src/js/worker.js 404 (Not Found)

我创建了一个 worker.js 文件,文件中有以下代码

this.addEventListner('message', function(e){
   console.log('Message received: ', e.data);
});

下面的代码向工作人员发送消息

let worker = new Worker('src/js/worker.js')
worker.postMessage('hello');

有人可以告诉我我做错了什么吗?谢谢!

【问题讨论】:

  • 当您打开开发者工具并查看“网络”选项卡时,请求的 URL 是否符合您的预期?
  • @Xufox,是的,请求 URL 符合我的期望

标签: web backbone.js marionette web-worker


【解决方案1】:

您似乎尝试从不安全的位置加载服务工作者脚本。我建议您从http://localhost 为您提供开发页面,以便与服务人员一起迈出第一步。您会在 "Is ServiceWorker Ready?" 网站上找到一个很棒的“路标”。

确保您:

如果没有有效的证书,您将无法从 httphttps 协议加载服务工作者脚本。从http://localhost 为您提供页面是一个例外; localhost 被认为是安全的,可以使开发更容易。另见the full list of "secure" origins as implemented in Chrome

如果文件丢失或浏览器无法从您使用的协议加载它,您将收到相同的错误:

A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE
ServiceWorker registration failed:  TypeError: Failed to register a ServiceWorker:
  A bad HTTP response code (404) was received when fetching the script.

如果您网站的 SSL 证书无效,包括自签名证书,您将收到以下错误:

An SSL certificate error occurred when fetching the script.
Failed to load resource: net::ERR_CERT_DATE_INVALID
ServiceWorker registration failed:  DOMException: Failed to register a ServiceWorker:
  An SSL certificate error occurred when fetching the script.

如果您使用自签名证书,您可以install the SSL certificate of your "fake" CA as a trusted root certificate authority in your web browser 或操作系统。浏览器在访问您的页面时不会再询问您是否有异常,并且 service worker 会很好地加载。

如果您使用 Chrome,可以使用参数--unsafely-treat-insecure-origin-as-secure--allow-insecure-localhost 强制浏览器使用load the service worker script from otherwise illegal origins。但仅在您的开发环境中执行此操作。不在生产网站上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多