对获取“url”的访问已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。ReactJS

lsp*_*iro 20 javascript python reactjs fetch-api google-cloud-functions

我正在尝试使用以下代码从开发模式下的 React 应用程序获取无服务器函数。

let response = await fetch(url,
       {
           method: 'POST',
           mode: 'cors',
           body: "param=" + paramVar,
        })
        .then(response => response.json());
Run Code Online (Sandbox Code Playgroud)

后端函数是一个Python Cloud函数,代码如下:

def main(request):
    # CORS handling
    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': '*',
            'Access-Control-Allow-Methods': 'GET, POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)
    
    # Set CORS headers for the main request
    headers = {
        'Content-Type':'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
    }

    # Process request
    return (json.dumps(response), 200, headers)
Run Code Online (Sandbox Code Playgroud)

但我不断收到以下错误:

Access to fetch at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
Run Code Online (Sandbox Code Playgroud)

当我尝试使用curl 执行相同的请求时,我得到了正确的响应。使用curl 获取选项给我以下结果:

HTTP/2 204
access-control-allow-headers: Content-Type
access-control-allow-methods: GET, POST
access-control-allow-origin: *
access-control-max-age: 3600
content-type: text/html; charset=utf-8
date: Sun, 16 Aug 2020 01:29:41 GMT
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我理解为什么我无法在前端得到响应?标头中存在“Access-Control-Allow-Origin”,因此我真的不明白此错误的原因是什么。

lsp*_*iro -2

实际上,后端存在一个错误,该错误仅由浏览器添加的一些附加标头触发。在这种特殊情况下,服务器返回 404 错误,该错误不包含我的标头定义,并会导致 CORS 策略阻止。

在我使用 devtools 跟踪浏览器发送的请求并复制我的curl请求中的所有标头后,我才能够识别出该错误。修复了功能逻辑后问题就解决了。

  • 嗯,由于这些帖子应该是为了帮助整个社区,您能否更详细地描述一下您是如何(哪些标题?)解决这个问题并提供代码示例的? (4认同)