title: How to Redirect to Single Page Web App in Express for Node
body: <p>I am writing a website with a single page web app (the rest of the website is just static files which are served). I am trying to write a piece of middleware for express to redirect all requests that follow the pattern 'example.com/app' to 'example.com/app' so that requests such as 'example.com/app/my/specific/page/' will all result in the same page being sent. The key issue with this is that the url in the address bar of the browser must not change so that the javascript app itself can interpret it and display the correct thing.</p>
  
  <p>I could have done something like this:</p>
  
  <pre><code>app.use( '/app', function ( req, res ) {
      res.redirect('/app');
  });
  </code></pre>
  
  <p>However, this causes the url of the page to change and a separate HTTP request is assumedly made.</p>
  
  <p>The most obvious alternative solution is to do something like this:</p>
  
  <pre><code>app.use( '/app', function ( req, res ) {
      res.sendfile(__dirname + '/public/app/index.html');
  });
  </code></pre>
  
  <p>The issue here is that resources from the page after requests like 'example.com/app/my/specific/page/' will look in the wrong location. For example, if I have an image on the page such as  then it will look for example.com/app/my/specific/page/image.jpg. Since no image is returned, it will not display on the page. This happens for all external scripts or stylesheets.</p>
  
  <p>I also tried something like this:</p>
  
  <pre><code>app.use( '/app', function ( req, res ) {
      res.sendfile(__dirname + '/public/beta' + url.parse(req.url).pathname);
  });
  </code></pre>
  
  <p>but that was very stupid of me for obvious reasons.</p>