html - 使用 NodeJS 和 ExpressJS 托管静态渐进式 Web 应用程序 (PWA)

标签 html node.js express localhost service-worker

我正在尝试使用 ExpressJS 托管静态渐进式 Web 应用程序,但由于我对 Web 开发相当陌生,所以遇到了一些麻烦。

我发现了许多关于如何使用 ExpressJS 进行路由的精彩文章(请参阅下面的链接),但没有一篇可以帮助我解决问题。这些教程非常基础,我找不到任何更高级的教程 - 如果你们知道任何教程,请回复此帖子并链接它们!

https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
https://stormpath.com/blog/build-nodejs-express-stormpath-app
https://zellwk.com/blog/crud-express-mongodb/
https://www.codementor.io/nodejs/tutorial/build-website-from-scratch-using-expressjs-and-bootstrap

我的文件夹结构如下所示:

node_modules
package.json
server.js 
index.html
sw.js (service worker)
public/
    js/
        index.js
    style/
        index.css

我的 server.js 看起来像这样:

var express = require('express');
var app = express();

// Initialize static content
app.use(express.static('public'));

app.get('/index.html', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});
app.listen(8887);

在我的index.html中,我正在加载我的public/style/index.css样式表和public/js/index.js javascript,如下所示:

<link rel="stylesheet" href="public/style/index.css">
<script src="public/js/index.js"></script>

当我使用命令“node server.js”托管我的应用程序时,我导航到 http://localhost:8887/index.html ,然后我得到正确的index.html 文件,但没有index.css 文件。

这是我的问题:

  1. 我的样式表未正确提供(index.html 呈现 没有任何 CSS)
  2. 浏览器未获取 Service Worker (sw.js)

编辑:将 sw.js 移动到 public/文件夹会在服务工作线程加载时导致错误:GET http://localhost:8887/sw.js net::ERR_INVALID_RESPONSE。

编辑 2:更多服务工作人员错误:More service worker errors

最佳答案

我建议像这样注册快速静态:

var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));

然后,像这样引用您的脚本:

<link rel="stylesheet" href="/style/index.css">
<script src="/js/index.js"></script>

服务人员正在做什么?

关于html - 使用 NodeJS 和 ExpressJS 托管静态渐进式 Web 应用程序 (PWA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39998237/

相关文章:

node.js - Swagger JSDoc 不从子文件夹加载 API 文件

javascript - 我想为每个从 mysql 数据库登录的用户发送唯一记录

javascript - 如何将 OneSignal 订阅链接 (javascript) 变成按钮?

php - 为 HTML 编码 mySQL 文本?

node.js - 如何删除 Node.js 中的 Cognito 用户?

node.js - 我们可以使用 MongoDB 进行临时存储吗?

javascript - Pug 有条件包含文件路径的所有子目录

javascript - 如何在 ExpressJS 中创建可扩展 Controller

html - 使用 CSS 合并节标签的边框颜色

javascript - 相对于滚动位置定位 div