Search code examples
javascriptnode.jsbrowserstatic-files

Serving static html files with nodejs with default prefix


I am using Restify to serve my static webpage. The html file calls the server for scripts and css files.

The server that I am creating needs to have all endpoints prefixed with /safe/endpoint

I have been able to server the index.html file but when the browser tries to include the script and css files I get a 404 status code.

When I go to localhost:1337/safe/endpoint I get the index.html which renders correctly. But when the browser tries to download the other files it prefixes the path in the index.html with localhost:1337/safe instead of localhost:1337/safe/endpoint.

example:

the index.html is served with this path

localhost:1337/safe/endpoint

in the index.html file I have this include

<script src="app/js/thing.js"></script>

when the browser tries to get the thing.js in uses this path

localhost:1337/safe/app/js/thing.js

instead of

localhost:1337/safe/endpoint/app/js/thing.js

The server code looks like this

server.get("/safe/endpoint", function(req, res){
  fs.readFile("./frontend/index.html", "utf8", function(err, data){
    if(err){
      res.setHeader('content-type', 'text/plain');
      res.send(404, "No index.html found");
    } else {
      res.setHeader('Content-Type', 'text/html');
      res.writeHead(200);
      res.end(data);
    }
  });
});

server.get("/safe/endpoint/app/.*", function(req, res){
  var filePath = "./frontend" + req.url.split("/safe/endpoint")[1];

  fs.readFile(filePath, "utf8", function(err, data){
    if(err){
      res.setHeader('content-type', 'text/plain');
      res.send(404, req.url + " not found");
    } else {
      res.setHeader('Content-Type', 'text/html');
      res.writeHead(200);
      res.end(data);
    }
  });
});

Solution

  • I was able to get this working with the serveStatic included in the restify module

    server.get("/safe/endpoint/.*", restify.serveStatic({
      directory: "./UI",
      default: "index.html"
    }));
    

    but I needed to prefix the folder path in the UI folder:

    /UI/safe/endpoint/index.html
    

    But there is one downside of this. When requesting to the server the path needs to be

    example.com/safe/endpoint/
    

    instead of

    example.com/safe/endpoint