Using Azure Functions Proxies to Solve CORS Issues
By Harry Bellamy
- 2 minutes read - 408 wordsRecently I’ve been delving into some Angular development and found it a nice change of pace from the C#/Azure/ops things I’m usually involved with.
To (re)familiarise myself with the syntax, I created a basic dashboard to load data from my Goodreads account (Goodreads provides a series of RSS feeds to supply data from your account).
As this is effectively a public API (yes, anyone can access your Goodreads RSS feeds!), there was no CORS header (Access-Control-Allow-Origin
) on the responses. Out of the box, Angular is very picky about CORS issues (with good reason), meaning that my local development server could not connect to it directly.
To get round this, initially I configured the proxy feature to trick Angular into thinking that the response was from the same origin.
However, this approach only works for local development - when I pushed my new site out to Azure Static Web Apps, all the API endpoints were inaccessible due to the proxy feature not working.
Azure Functions Proxies to the Rescue
Azure Functions Proxies allow us to have similar functionality to Angular Proxies but with the advantage that they work for both running locally and code deployed in the cloud.
Setup
To create an Azure Functions Proxy you will first need to create an Azure Functions resource (you can use an existing one if you already have one).
The Proxies section can be found here:
Once in the Proxies section, click ‘Add’. From here you can configure your new proxy.
In the example above, a new proxy is being created called ‘MyNewProxy’. The Route Template determines where the URL of the proxy relative to the root of the function (this can be found on the home page). I have selected only get methods to be supported, but all HTTP methods can be allowed. Finally, the backend URL determines the URL to be called by the proxy.
There are further settings but they were not needed for this use case.
Enabling CORS
The final thing to do to get this working with a local development server is to add a CORS allowed origin to the function.
To do this, navigate to the following page and add http://localhost:4200
(the default Angular local development URL) as an allowed origin.
Note that this adds this adds an Allowed Origin for all functions in the resource, not just the proxy(ies).
This adds an Access-Control-Allow-Origin
header with the correct origin specified, allowing localhost to connect to it.