使用NodeJS和ExpressJS托管静态Progressive Web App(PWA)

时间:2016-10-12 12:08:26

标签: html node.js express localhost service-worker

我正在尝试使用ExpressJS托管静态渐进式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. 浏览器未获取服务工作者(sw.js)
  3. 编辑:当服务工作者加载时,将sw.js移动到public /文件夹会导致错误:GET http://localhost:8887/sw.js net :: ERR_INVALID_RESPONSE。

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

1 个答案:

答案 0 :(得分:1)

我建议像这样注册express static:

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>

服务人员在做什么?