python - 如何在 Azure Functions API (Python) 中处理 CORS

我正在尝试对我部署的用于检索 JSON 数据的 Azure 函数进行 POST。我收到 CORS 错误。

有权从来源“http://localhost:3000”在“{API URL}”获取数据' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

我的前端使用 javascript 发送 POST 请求:

    const data = { name: "jennifer" };

    const response = fetch(url, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': "http://localhost:3000",
            'Origin': 'http://localhost:3000'
        }
    })

我的后端处理 CORS 预检:

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    headers = {
            "Access-Control-Allow-Origin" : "http://localhost:3000",
            "Access-Control-Allow-Credentials" : "true",
            "Access-Control-Allow-Methods" : "GET, POST, OPTIONS",
            "Access-Control-Allow-Headers" : "Origin, Content-Type, Accept"}

    #handle CORS preflight
    if req.method == "OPTIONS":
        return func.HttpResponse(headers=headers)

我是否错误地处理了预检?

最佳答案

我通过从消费计划迁移到应用服务计划“解决”了这个问题。这使我能够使用其精美的 UI 配置 CORS。

@AnthonyChu 建议

If you want to stay on Azure Functions' consumption plan, you can use Azure API Management consumption tier in front of your function app to add a CORS policy."

关于python - 如何在 Azure Functions API (Python) 中处理 CORS 预检?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57211544/

相关文章:

redux - 将 Prop 传递给 redux 初始状态

python - 如何在 Django 的运行服务器中进行事后调试?

css - 自托管字体在 Gatsby 和 Safari 中不起作用

python - AWS Lambda——无法为 SpaCy 导入 srsly.ujson.ujso

reactjs - react Hook : Idiomatic way to ensure tha

javascript - 无法让用 chrome 录制的音频 blob 在 safari 中工作

angular - Froala 编辑器 formControl 在第二次加载后不更新

macos - 错误 : command 'gcc' failed with exit status

javascript - `npm install`后出现关于python语法错误的错误?

php - LinkedIn Share API 'ugcPosts' 响应 504 PHP 网关超