我正在尝试将服务人员注册到html页面,并且标题显示错误。 我在linux上工作,我有权写,删除,修改等等(我在#上)。 我正沿着:
/var/www/a/b/c/d/e/f/project
在这里,我有一个node.js服务器(index.js),html页面(index.html)和服务工作者(ServiceWorker.js)
node.js服务器看起来像:
const https = require('https');
const fs = require('fs');
var path = require('path');
const express = require('express');
const app = express();
const router = express.Router();
const pool = require('./mysqldb.js');
const pathView = __dirname + "/views/";
const IMGPath = "/public";
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'));
// This route will be used to print the type of HTTP request the particular
Route is referring to
router.use(function (req, res, next) {
next();
});
app.engine('html', require('ejs').renderFile);
app.get('/index.html',function(req,res){
res.render('/var/www/a/b/c/d/e/f/project/index.html');
});
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( listenPort )
});
//HTTPS
https.createServer(options, app).listen(8000);
.html文件如下:
<html>
<body>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('ServiceWorker.js', {
scope: './'
}).then(function (registration) {
var serviceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
document.querySelector('#kind').textContent = 'installing';
} else if (registration.waiting) {
serviceWorker = registration.waiting;
document.querySelector('#kind').textContent = 'waiting';
} else if (registration.active) {
serviceWorker = registration.active;
document.querySelector('#kind').textContent = 'active';
}
if (serviceWorker) {
// logState(serviceWorker.state);
serviceWorker.addEventListener('statechange', function (e) {
// logState(e.target.state);
});
}
}).catch (function (error) {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contain a syntax error.
console.log('Service Worker registration error : ' , error);
});
} else {
console.log('Please update your brower!');
// The current browser doesn't support service workers.
}
</script>
</body>
</html>
我运行index.js节点(命令:“ node index.js”) 一切都很好,页面正在加载(我的意思是页面中的脚本),并且出现以下错误:
Service Worker registration error : TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
我不知道该怎么办。我基本上在同一文件夹中有ServiceWorker.js,index.html和index.js。我尝试运行它们,但是路径不正确... 有人可以帮我吗?
答案 0 :(得分:0)
将其包含在app.js中,并将服务工作人员放在公共目录/文件夹中。
notty