Sunday, March 29, 2020

how to fix "Access to XMLHttpRequest at 'http://localhost:7071/api/' from origin 'http://localhost:3000' has been blocked by CORS policy" in Azure Serverless implementation?

when i implemented the Web API using Azure functions in Azure Serverless development. i try to run the Azure fucntion in the localhost from visual studio code. the error came up immdiately after i test the create function.

"Access to XMLHttpRequest at 'http://localhost:7071/api/createSpeaker/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

the error message clearly indicated that it was a CORS issue. which is the web app hosts on port 3000 and tries to access the web API hosts on port 7071.

according to the microsoft document. it suggested that we should add the following configuration to the local.settings.json file which is the configure file for azure functions running in local mode.

https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash

"Host": {
    "LocalHttpPort": 7071,
    "CORS": "*",
    "CORSCredentials": false
  },

however the above never works for me. acutally the following command line did fix the issue

func host start --cors *

Happy programming and enjoy the fun




No comments:

Post a Comment