【Azure Function】Function本地调试时遇见跨域问题(blocked by CORS policy)

问题描述

在本地调试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.

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

 

问题解答

可以的。

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

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

文件名:local.settings.json

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

测试效果(成功):

 

参考资料

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

posted @ 2024-02-01 21:02  路边两盏灯  阅读(14)  评论(0编辑  收藏  举报