类型错误:无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404) [英] TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script
问题描述
我正在尝试向网站添加 Service Worker.我将 Node.js 与 Express.js、Vue.js 和 EJS 结合使用.^
I'm trying to add a service worker to a website.I'm using Node.js with Express.js,Vue.js and EJS.^
我的节点服务器(index.js)看起来像:
My node server (index.js) looks like :
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
const router = express.Router();
const pool = require('./mysqldb.js');
const pathView = __dirname + "/views/";
var bodyParser = require("body-parser");
const listenPort = 8010;
// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// Process application/json
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public', express.static('public'));
router.use(function (req, res, next) {
next();
});
// home
router.get('/', function (req, res) {
res.render( 'home.ejs', { msg:" > " });
});
app.use( "/", router);
// Not found
app.use("*",function(req,res){
res.setHeader('Content-Type', 'text/html');
res.status(404).send('Page introuvable !');
});
// Run server
app.listen(listenPort, function () {
console.log('Example app listening on port ' + listenPort )
});
home.ejs 文件如下所示:
And the home.ejs file looks like:
<!DOCTYPE html>
<html lang="en">
<body>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('ServiceWorker.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
//registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}else {
console.log('No service-worker on this browser');}
</script>
</body>
</html>
我不得不提一下,我正在 https 上测试它.我不认为 ServiceWorker.js 的内容那么重要,但是如果您需要它来帮助我,我也可以发布它.服务器文件方案如下所示:
I have to mention that I'm testing it on https. I don't think the content of ServiceWorker.js is that importat,but if you would need it to help me I can post it too. The server files scheme would look like:
index.js
mysqldb.js
public //(folder)
views /*(folder)*/ : home.ejs , ServiceWorker.js
当我在 https 打开网站时,我在 Web 控制台中收到以下错误:
And when I open the website on https I get the following error in web console:
ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
推荐答案
ServiceWorker.js
位于您的 views
文件夹中.这适用于通过 express 作为页面呈现的模板.将其移动到 public
以便它像静态文件一样提供.
ServiceWorker.js
is in your views
folder. That is for templates that get rendered by express as a page. Move it to public
so that it gets served like a static file.
这篇关于类型错误:无法注册 ServiceWorker:获取脚本时收到错误的 HTTP 响应代码 (404)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!