This is one of those things that you keep running into when working with Azure functions. And maybe just enough time have passed since the last time, so its a question of “how did I fix this again?”. To save myself (and hopefully you) some time in the future – here is a tiny blogpost with the solution.
If you’re new to the magic lands of development you might not know what CORS is, so I’ll add a short explanation. If you just want to run your azure function locally without issues you can jump straigt to the solution.
What is CORS and why do we need it?
Cross-Origin Resource Sharing, or CORS for short, is a mechanism that allows a server to say which origins are allowed to ask for resources. You can read more about the technical details it in the mdn web docs. This is a topic large enough to require its own blogpost to cover all the details – so for now I’ll just give you an overview.
On the one side you have a SPfx webpart that lives on a sharepoint site “yourdomain.sharepoint.com”. And on the other side you have an azure function that lives in your azure environment.
Our browsers enforce the principle of “same origin policy”, so as long as your app is living on the web – your browser will stop it from talking to you function if its not configured to allow a request from your app. When your azure function is deployed to azure you can configure the CORS settings of the functional app where the function lives. But as long as it is running locally your app wont be allowed to talk to it – unless you run your app locally too.
If you try you will get a response that looks something like:
Access to fetch at ‘http://localhost:7071/yourFunction' from origin ‘https://yourdomain.sharepoint.com' 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.
Solution – add a host section to your local.settings.json file
Open up your local.settings.json file. As you can see in the image below this file does not contain much ‘out of the box’.
What you need to to is add a host section with portnumber and CORS, like in the snippet below:
{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "", "FUNCTIONS_WORKER_RUNTIME": "node" }, "Host": { "LocalHttpPort": 7071, "CORS": "*" } }
Restart your function and you should now be able to call it from your app without getting CORS issues.
Did you find this article usefull? Follow me on twitter to be notified when I publish something new!
If you are interested in Azure functions you might also like my other blogposts in this category.
Also, if you have any feedback or questions, please let me know in the comments below. 🙂
Thank you for reading, and happy coding!
/Eli
If you want to support my content you can