Express server for an Angular application part 3: redirect routes to an external service

Express.js is a web application framework for Node.js designed for building web applications, in this series of articles I will explain step by step how i realized an express server with some advanced functions that i use for my single page application made with Angular 7.

I will discuss the 7 main problem that i solved in different articles:

  1. getting started
  2. serve files from a bucket
  3. redirect some calls to an external service
  4. redirect http to https requests
  5. redirect non-www to www requests
  6. limit connections and prevent ddos
  7. handle some cache

In this third article I will discuss how to handle some special routes and redirect them to external services.

Reference repository

A working example of this project is available at: the master branch contain the final full project but there’s a dedicated branch for every single article, for this one the reference is:

The Example

A classical example, and the reason why I added this feature to my server, is the sitemap.xml file. If your frontend application manage some CMS features and retrieve contents from API is totally reasonable to assume that the sitemap is generated by the backend. There are many solutions to this problem, like a dedicated api parsed by Angular, but the most lightweight solution is proxy the request for the sitemap to your backend.

Let’s assume that your backend server make available the sitemap on a known path and add this variable to your code:

const _apiAddress = ‘https://testapi/api/example/sitemap';

With a little improvement to your code you will be able to serve this file.

Proxy the external route

After the declaration of your “app” variable add:

this simple code fragment handle all the requests to xml files and serve them by piping the result of the external call.

This is a simple implementation but you can change your regex or the backend call for more complex behaviors.

Test it

Run your application with

$node server.js

and go to http://localhost:4100/sitemap.xml and express will serve the result of the external service https://testapi/api/example/sitemap.

In the next article I will discuss http and https request and how to manage them.