Normally, building an Angular application with an ExpressJS server powering it would be straight forward and it is but problems creep in if when you deploy it to your NginX backed server, like I found out the hard way.
Generally, there are 2 ways to serve an Angular app -
Example 1
app.get('/api/user', user.get); // your api endpoint
app.get('*', view.index); // let angular do the rest
Example 2
app.get('/api/user', user.get); // your api endpoint
app.get('*', function (req, res) {
res.render('index.html'); // let angular do the rest
});
In the first example, you would be using a rendering engine to serve the default view from your views
folder containing all the code to fire up your Angular app. In the second one, you would be serving the index.html
directly from your public
folder.
The problems lies in the second example. Your application will have no problem when working on your development machine. Your angular app will be served properly with pretty URLs (I’ve assumed from the start that you use HTML5 mode in Angular) and it will be able to call all your API endpoints like normal.
If you use NginX as the reverse proxy to host your final application, the latter example will not work though. Firing off an API call from your Angular app will hang and after about 5 minutes, you will receive a 404.
Thing is, NginX has a tough time routing when you are serving your HTML file directly from the public folder along with your API endpoints. The fix, after hours of reading through the documentation is one liner fix. The fix, as you’ll see will let you serve your index.html
directly from the public
folder and still get the benefits of HTML5 mode in Angular.
The fix -
// your endpoint routes go here
app.get('*', function(req, res) {
res.redirect('/#' + req.originalUrl);
});