gpt4 book ai didi

javascript - 类型错误 : Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script

转载 作者:行者123 更新时间:2023-11-30 20:09:16 28 4
gpt4 key购买 nike

我正在尝试向网站添加服务 worker 。我正在将 Node.js 与 Express.js、Vue.js 和 EJS 结合使用。^

我的 Node 服务器(index.js)看起来像:

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 文件如下所示:

<!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 的内容那么重要,但如果你需要它来帮助我,我也可以发布它。服务器文件方案如下所示:

  index.js
mysqldb.js
public //(folder)
views /*(folder)*/ : home.ejs , ServiceWorker.js

当我在 https 上打开网站时,我在 Web 控制台中收到以下错误:

  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,以便它像静态文件一样提供服务。

关于javascript - 类型错误 : Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52568560/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com