获取“url”的访问被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' header。响应式JS

Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS

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

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

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

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)

但我不断收到以下错误:

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.

当我尝试使用 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

任何人都可以帮助我理解为什么我无法在 front-end 上收到回复? 'Access-Control-Allow-Origin' 出现在 headers 中,所以我真的不明白这个错误的原因是什么。

将 content-type header 添加到前端的获取方法中,然后重试:

let response = await fetch(url,
       {
           method: 'POST',
           mode: 'cors',
           body: "param=" + paramVar,
           headers: {
             'Content-Type': 'application/json'
       },
  }).then(response => response.json());

在后端安装 CORS 包。 然后打开您的 server.js 文件或任何您的文件。 然后导入到文件

const cors = require('cors');

然后使用它

app.use(cors());

重新加载浏览器,应该完成了!

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

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