Search code examples
angularexpressproduction-environment

How to configure express to serve angular app in production?


There is common problem with client-side routing mechanism: once it is deployed, so called "deep links" like host/deep/deeper/deepest/link/1 spits out 404 Not Found rahter then gets propagated to the index.html and resovled properly to a certain component.

How do I configure it?

I tried:

app.use(express.static(root)); // root folder of the project
app.use((req, res) => res.sendFile(path.join(__dirname, root,'index.html')));

...and yet it works only with base url; all others are rejected.


Solution

  • app.use(express.static(root)); // root folder of the project
    

    This means a middleware function with no mount path. This code is executed for every request to the router

    try to use look like this

      app.use('/', express.static(path.join(__dirname, '../root')));
    
      app.get('/*', function(req, res) {
        res.sendFile(path.join(__dirname, '../root/index.html'));
      });
    

    The complete example is here https://github.com/mdshohelrana/mean-stack/blob/master/server/app.ts