繁体   English   中英

GCP Cloud Function HTTP 触发器“没有'Access-Control-Allow-Origin' header 存在于请求的资源上。” 错误

[英]GCP Cloud Function HTTP trigger “No 'Access-Control-Allow-Origin' header is present on the requested resource.” error

我有一个带有 HTTP 触发器的 GCP Cloud function。 我做了一个测试反应前端,需要用 HTTP 请求触发这个 function。

这是发出该请求的代码:

    async function handleSubmit() {
        const url = 'https://us-central1-{project-id}.cloudfunctions.net/hello-test';
        const data = {name:"Jane"};

        const response = await fetch(url, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(data), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json'
            }
        });
        await response.json();

    }

这里是云function:

def hello_http(request):
    # Set CORS headers for preflight requests
    if request.method == 'OPTIONS':
        # Allows GET requests from origin http://localhost:3000 with
        # Authorization header
        headers = {
            'Access-Control-Allow-Origin': 'http://localhost:3000',
            'Access-Control-Allow-Methods': 'POST', #GET???
            'Access-Control-Allow-Headers': 'Authorization',
            'Access-Control-Max-Age': '3600',
            'Access-Control-Allow-Credentials': 'true'
        }
        return ('test return value')

    # Set CORS headers for main requests
    headers = {
        'Access-Control-Allow-Origin': 'http://localhost:3000',
        'Access-Control-Allow-Credentials': 'true'
    }

    return ('another test return value')

这是我从本地反应应用程序运行此代码时遇到的错误:

Access to fetch at 'https://us-central1-{PROJECT-ID}.cloudfunctions.net/hello-test' 
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. If an opaque response serves your needs,
 set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这个云 function 在我使用时按预期工作:

curl -X POST HTTP_TRIGGER_ENDPOINT -H "Content-Type:application/json" -d '{"name":"Jane"}'

让这个请求处理作为 POST 请求发送的数据 object 和从云 function 返回的字符串的任何帮助都将解决我的问题。

谢谢你。

编辑: curl -i -X OPTIONS {url} 的结果

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Max-Age: 3600
Content-Type: text/html; charset=utf-8
Function-Execution-Id: roz4rhywam83
X-Cloud-Trace-Context: 9d52fb9b30e029f32c2a787ad0d006d2;o=1
Date: Thu, 21 Nov 2019 20:03:54 GMT
Server: Google Frontend
Content-Length: 15
Alt-Svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000

这个解决方案对我有用:

const response = await fetch(url, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(data), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        }).then(res => res.text());

        console.log(response)
    }

其中数据是 json object 和 url 是云函数 Z572D4E421E5E6B9BC11D815E8A0。

这是云 function。

def app_run(request):
    # For more information about CORS and CORS preflight requests, see
    # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
    # for more information.

    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',  # http://localhost:3000',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }



    return ('return value', 200, headers)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM