【Azure Function】Function本地调试时遇见跨域问题(blocked by CORS policy) - LuBu0505/My-Code GitHub Wiki

问题描述

在本地调试Azure Function时,遇见了跨域问题:

Access to XMLHttpRequest at 'http://localhost:7071/api/HttpTriggerToken?tenantId=b7f6f99f-3045-412a-8828-b3044070857e&documentId=6a8ffc27-026f-498e-9936-f6c55db558e5&userId=test-user&userName=Test+User' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. image.png

是否有办法区解决这个问题呢?

问题解答

可以的。

在本地的调试中,可以修改Function本地的配置文件(local.setting.json),在其中添加CORS配置为通配符”*”,即可解决这个问题。

CORS  定义跨域资源共享 (CORS)可以使用的来源。 以逗号分隔的列表提供来源,其中不含空格。 支持通配符值 (*),它允许使用任何来源的请求。

文件名:local.settings.json

{
 "IsEncrypted": false,
 "Values": {
   "AzureWebJobsStorage": "",
   "FUNCTIONS_WORKER_RUNTIME": "node"
 },
 "Host": {
   "CORS": "*"
 }
} 

测试效果(成功): function cors setting.gif

参考资料

Function本地配置文件:https://docs.azure.cn/zh-cn/azure-functions/functions-develop-local#local-settings-file

Azure Functions, localhost and CORS how to get them working together when debugging locally : https://sebastian-rogers.medium.com/azure-functions-localhost-and-cors-how-to-get-them-working-together-when-debugging-locally-e48be40a411f

image.png

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!