Content negotiation for MEAN stack apps

For Angular applications to be completely connected to the back-end API, that is, NodeJS and ExpressJS, configuring Express so that it knows where to find the static assets is not enough.

Oftentimes I see express being configured to render for example the index.html when the application loads, what I never came across during the learning process is how I would handle page refreshes, this caught me because when the application is refreshed and the corresponding end-point knows only about responding with the requested JSON resource and not with the HTML view you are on in the client side, you get back a blank page with the JSON response from the end-point.

This is due to the fact that a client side page refresh is a GET request and thus the server will respond with the resource if of course the resource URL is valid and the HTTP request options where valid.

Here is an example of configuring Express to know the location of the client static assets

// the distribution folder is where the static assets will be in after some module bundler has finished doing it's work
app.use(express.static(path.join(__dirname, '/client-app/dist/')));

Now to handle all GET requests and negotiate their content, the code needs to be flexible, and note that in your client request options you have to specify the type of content you are expecting, something like

const headers: Headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + token);

And then back to your back-end, Express handles all GET requests and negotiates their responses based on the header options you have set with the request like so

app.get('/*', function(req, res, next) {
if (req.header('Content-Type') == 'application/json') {
next();
} else {
res.status(200).sendFile(__dirname + '/client-app/dist/index.html');
}});

There you have it, hope it helps!