Antag
Antag

Reputation: 230

Using NodeJS and ExpressJS to host a static Progressive Web App (PWA)

I am trying to host a static Progressive Web App using ExpressJS, but since I'm fairly new to web dev I'm having some trouble.

I have found a number of great articles on how to use ExpressJS for routing (see links below), but none of them have helped me resolve my problem. These tutorials are quite basic and I can't find any tutorials which are more advanced - if you guys know of any please reply to this thread and link them!

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

My folder structure looks like this:

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

and my server.js looks like this:

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);

In my index.html I am loading my public/style/index.css stylesheet and public/js/index.js javascript like this:

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

When I host my app using the command 'node server.js' and I navigate to http://localhost:8887/index.html, then I get served the correct index.html file but without the index.css file.

Here are my problems:

  1. My style sheets aren't being served correctly (index.html renders without any css)
  2. The browser is not picking up the service worker (sw.js)

Edit: Moving sw.js to the public/ folder causes an error when the service worker loads: GET http://localhost:8887/sw.js net::ERR_INVALID_RESPONSE.

Edit 2: More service worker errors: More service worker errors

Upvotes: 2

Views: 5115

Answers (1)

Stavros Zavrakas
Stavros Zavrakas

Reputation: 3053

I would suggest to register the express static like that:

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

and then, reference your scripts like that:

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

What the service worker is doing?

Upvotes: 2

Related Questions