From 54b911bcd4abd3f09844adb83dabed4632f1f7b2 Mon Sep 17 00:00:00 2001 From: Marsell Kukuljevic Date: Mon, 26 Apr 2021 22:32:35 +0200 Subject: [PATCH] When server.js receives a static path it does not recognize, it serves up index.html instead. This is useful when a user reloads a page in the SPA -- server.js does not know this path, but by serving up the SPA again the SPA knows how to handle that URL. This makes the app behave in a manner a user expects when reloading a page. --- bin/server.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/bin/server.js b/bin/server.js index 75bd31b..6ddc839 100755 --- a/bin/server.js +++ b/bin/server.js @@ -191,10 +191,25 @@ function main() { server.head(API_RE, proxy); // where to serve static content from - server.get(STATIC_RE, mod_restify.plugins.serveStatic({ + let staticHandler = mod_restify.plugins.serveStatic({ directory: 'static', default: 'index.html' - })); + }); + server.get(STATIC_RE, function staticFunnel(req, res, next) { + staticHandler(req, res, function fileFound(err) { + // If we didn't find the requested static file, serve up the + // default (index.html) instead. This is useful when a user reloads + // some page in the SPA, since the path does not match anything the + // backend knows, but the SPA reloaded through index.html will know + // what to do with the original URL. + if (err && err.statusCode === 404) { + req.url = '/'; + staticHandler(req, res, next); + } else { + next(err); + } + }); + }); // enable HTTP server server.listen(CONFIG.server.port, function listening() {