Skip to content

Instantly share code, notes, and snippets.

@starovoitovs
Created August 15, 2018 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starovoitovs/eb028c92d382b010681d35aa3743d078 to your computer and use it in GitHub Desktop.
Save starovoitovs/eb028c92d382b010681d35aa3743d078 to your computer and use it in GitHub Desktop.
Simple express server that admits HTML5 routing
const express = require("express");
const compression = require("compression");
const url = require("url");
const path = require("path");
const PORT = 4200;
// resolve pathname whether it is a static file or rewrite it to index.html (default start page for all pages)
const getFilename = (req) => {
const pathname = url.parse(req.url).pathname;
// serve static files
if (pathname.match(/.*(js|css|scss|jpg|jpeg|gif|ico|png|bmp|csv|doc|pdf|ttf|eot|eps|swf|woff|woff2|svg)$/)) {
return pathname;
}
// if not static, rewrite
return 'index.html';
};
const app = express();
app.use(compression());
app.get('*', function (req, res) {
const filename = getFilename(req);
res.sendFile(path.join(__dirname, "dist/frontend", filename));
});
app.listen(PORT, function () {
console.log("Listening on " + PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment