Introduction

During the development of applications that consume external APIs, it is common to encounter a problem known to many: CORS (Cross-Origin Resource Sharing). If you work with Fluig and develop locally with Angular, you have probably seen that annoying error in the console:

Access to XMLHttpRequest at ‘https://fluig.seuservidor.com/api/...' from origin ‘http://localhost:4200’ has been blocked by CORS policy…

But don’t worry, there is a simple and efficient way to overcome this obstacle during development without needing to change the Fluig server configuration: setting up a local reverse proxy in Angular.

Understanding the Problem

CORS is a browser security mechanism that prevents a web application made in one domain (e.g., localhost:4200) from making requests to another domain (e.g., fluig.seuservidor.com) without proper permission. This is great in production but a nuisance during local development.

Since we do not have (or do not want) to change the Fluig settings to allow cross-origin requests, we can solve this by redirecting the requests locally.

The Solution: Using proxy.conf.json

The Angular CLI allows you to create a reverse proxy with just a configuration file. With this, it intercepts your local requests and redirects them as if they were coming from the same backend domain. Here’s how to do it:

  1. Create the proxy.conf.json file at the root of your Angular project with the following content:
{
  "/api": {
    "target": "https://fluig.seuservidor.com",
    "secure": true,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
  • Explaining each property:
    • "/api": indicates the path you want to intercept. Everything that starts with /api will be redirected.
    • "target": the address of your Fluig server.
    • "secure": true: informs that the target uses HTTPS. Set to false if you are using an invalid certificate on Fluig.
    • "changeOrigin": true: adjusts the Origin header of the request to match that of the target.
    • "logLevel": "debug": useful for debugging, shows in the terminal what is being redirected.
  1. Now, start the Angular server with the proxy enabled:
ng serve --proxy-config proxy.conf.json
  1. Done! Now when making calls to /api, for example http://localhost:4200/api/public/ecm/dataset, Angular will redirect to https://fluig.seuservidor.com/api/public/ecm/dataset, without encountering CORS.

Conclusion

This is a practical and quick way to avoid headaches with CORS during local development with Angular and Fluig. It avoids unsafe changes on the server and keeps the focus on what really matters: coding.

Moreover, this approach works with any external API, not just Fluig — making it a powerful tool in your development arsenal.