It all started by trying to over-engineer things with an Azure Function. And then it wouldn’t work! This blog post is mostly for me so that I can find this stuff later when I inevitably hit the same CORS issue.
I had gone through the whole Microsoft tutorial for JavaScript Azure Functions, and then tested my Azure Function locally and remote via Visual Code’s built-in unit testing. When I tried to get my application’s JavaScript to call the function, I was suddenly blocked by a CORS issue.
The Code
In my JavaScript, I have a very simple fetch call to my Azure Function:
fetch(`https://myfunction.azurewebsites.net/api/capturesubscribers?channelId=${channelId}`)
The Error
Invoking this led to the following error:
Access to fetch at 'https://myfunction.azurewebsites.net/api/capturesubscribers?channelId=REDACTED' from origin 'http://dev.local' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The Fix
A few Google results later, I found this StackOverflow question: https://stackoverflow.com/questions/45332131/call-azure-function-from-javascript
The answer here confirmed that this is a CORS configuration on the Azure side that needs to be done in the Portal. From Visual Code I right-clicked on my Azure function and selected Open in portal:
This popped open the Azure Portal to the correct function in my subscription. On the left pane, I then scrolled down to the API section and selected CORS.
A CORS management panel loads up where I can enter allowed origins:
From here I could add my local development URL and everything worked! HOORAY!
Obviously, later on I will have to add any staging or production hosting domains as well, but for now, I can move forward.
Just a question out of curiosity. Is this to do anything with planning to replace Vercel Next.JS Edge functions with Azure Serverless functions?
I’m not sure what you are looking at, but this is unlikely to be related to it. I have a personal project I am working on to learn different tech (TypeScript, JavaScript modules, etc.) and I wanted a way to host some of my JavaScript outside of the JS loaded in browser.
So I started playing with Azure Functions to find out how those worked! Years of being a .NET dev has not prepared me for what is going on these days with serverless and front-end script 🙂
I haven’t played with Vercel Edge functions either, so I should find a way to work that into this project too!