In a previous post I showed how build an Angular app and a Node api with Bazel. In this post I will take this a step further by throwing a Java Api into the mix.
My other post can be found here.
Cross Domain Requests
In the previous demo I relied on CORS to allow ajax request from the Angular application to a Node api. This is necessary since the api and the Angular application are hosted on different domains.
For security reasons, Ajax requests between different domains are by default blocked by browsers. Even just a difference in port counts as a different domain as far as this rule is concerned.
In this post I will show a different approach to cross domain communication.
Instead of CORS I will stand up a reverse proxy in Node and proxy through to the Java api.
The idea is that the Node application will serve the Angular application’s index.html page.
How can we access the Java api?
The Java api is on a different domain, so we can’t access it directly from the browser.
However, as soon as the Angular application is loaded it will be able to make Ajax request to the Node application that served index.html. These requests are allowed since the domain is the same.
The requests to the Node app will then be proxied through to the Java api.
I have included the Node api below:
As you can see, there are two routes in the api.
- The initial / route for serving index html
- The cars endpoint that gets proxied through to the Java backend.
Bazel Dev Server
The Bazel team has built a very nice dev server for bundling dev versions of Angular applications. This dev server works great, but there is no way to add proxying.
Still I would like to use it to build the dev bundle. No point in reinventing the wheel!
To incorporate the dev server in my Node app I have configured the dev server as a CDN that will serve the bundled Angular application.
This is why the index.html page served by the Node app has the following script tag:
This works since I am starting up the dev server side by side with the Node app.
The Java api is super simple. All it does is return a list of cars.
The Bazel part is inspired by this Bazel repo.
Here is the servlet:
Here is the BUILD file:
Building the Application
We now have three parts to build and start: Node application, Java api and the Bazel dev server.
To start all there I use concurrently in an npm start task:
You can find the code on Github if you are interested in trying it out.