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:
- getting started
- serve files from a bucket
- redirect some calls to an external service
- redirect http to https requests
- redirect non-www to www requests
- limit connections and prevent ddos
- handle some cache
In this third article I will discuss how to handle some special routes and redirect them to external services.
A working example of this project is available at:
https://github.com/mzuccaroli/express_server_for_angular_example the master branch contain the final full project but there’s a dedicated branch for every single article, for this one the reference is:
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.
Run your application with
In the next article I will discuss http and https request and how to manage them.