Azure Functions – Access has been blocked by CORS policy

Jason St-Cyr - Oct 3 '22 - - Dev Community

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}`)
Enter fullscreen mode Exit fullscreen mode

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:

Image of context menu in Visual Code showing option to 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:

A screenshot from the Microsoft Azure Portal showing the options to edit CORS allowed origins. The user has entered http://dev.local into the Allowed Origins section

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player