【问题标题】:CORS error when trying to call Google Cloud function from the front-end (Web site)尝试从前端调用 Google Cloud 函数时出现 CORS 错误(网站)
【发布时间】:2021-08-22 19:43:44
【问题描述】:

当我尝试从网站(前端)调用我的谷歌云功能时,我遇到了 CORS 问题。问题是我可以在 Jupyter notebook 中成功执行相同的代码而不会出错。到目前为止,我已经添加了启用 CORS 访问所需的所有内容,但我仍然遇到相同的错误(从源“http://localhost:3000”访问“https://****”处的 XMLHttpRequest被 CORS 政策阻止:请求的资源上没有“Access-Control-Allow-Origin”标头。有什么帮助吗?

以下是源代码:

import requests
import json
import flask
def myFunction(request):
    request_json = request.get_json()
    # preflight request
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        print ('', 204, headers)

    # main request
    headers = {
        'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
        'Access-Control-Allow-Origin': '*'
    }
#    Call to get a access token from a refresh token
    response = requests.post(url = "https://accounts.zoho.com/oauth/v2/...",headers = headers)
    accessToken = response.json()['access_token']
    # Call to zoho Api to insert a new lead
    url = 'https://www.zohoapis.com/crm/v2/Leads'
    v_access = 'Zoho-oauthtoken ' + accessToken 
    headers = {
            'Authorization': v_access,
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,GET, POST'
        }
    json_data = request.get_json(silent=True)
    newdata = json.dumps(json_data)
    v_data = str(json.loads(newdata))
    v_data1 = v_data.encode('utf-8')
    post_response = requests.post(url,headers = headers, data = v_data1)
    post_response.headers['Access-Control-Allow-Origin'] = '*'
    post_response.headers['Access-Control-Allow-Methods'] = 'GET, POST'
    return (post_response.status_code)

【问题讨论】:

    标签: google-cloud-functions cors


    【解决方案1】:

    您通常不想陷入手动处理 CORS 标头的困境,请尝试使用中间件,例如 https://flask-cors.readthedocs.io/en/latest/#route-specific-cors-via-decorator

    不过,特别是围绕您的响应,您实际上从不返回标题,只是一个状态代码。

    如果您在 GCP 上看到示例,您可以看到您需要在响应中设置 ACAO = * 标头。 https://cloud.google.com/functions/docs/writing/http#preflight_request

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }
    
    return ('Hello World!', 200, headers) // Need the Headers in the Response
    

    【讨论】:

    • 我尝试使用 Flask_cors 装饰器,但它也不起作用。以下是我添加到代码中的内容:` from flask import Flask from flask_cors import CORS app = Flask(name) CORS(app)` 在我的函数定义之前
    猜你喜欢
    • 2021-01-24
    • 2021-03-09
    • 1970-01-01
    • 2011-07-02
    • 2021-11-23
    • 1970-01-01
    • 2020-06-08
    • 2022-11-30
    • 2011-01-19
    相关资源
    最近更新 更多