javascript - 获取 `url` 的访问被 CORS 策略 : No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS 阻止

标签 javascript python reactjs google-cloud-functions fetch-api

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

let response = await fetch(url,
       {
           method: 'POST',
           mode: 'cors',
           body: "param=" + paramVar,
        })
        .then(response => response.json());
后端函数是一个 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)
但我不断收到以下错误:
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
任何人都可以帮助我理解为什么我无法在前端得到响应?标题中存在“Access-Control-Allow-Origin”,所以我真的不明白这个错误的原因是什么。

最佳答案

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

const cors = require('cors');
然后使用它
app.use(cors());
重新加载浏览器,应该完成!

关于javascript - 获取 `url` 的访问被 CORS 策略 : No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS 阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63432473/

相关文章:

javascript - 在 AJAX 调用中处理身份验证

javascript - subview 事件回调是否优先?

python - mypy可以识别自定义解包吗?

python - 数据框列到字典的字典中

python - 读取进程输出

reactjs - 如何使用 react-pdf 库创建表格以生成 pdf 报告?

javascript - 管理父切换案例

c# - Stop OnClientClick ="aspnetForm.target =' _blank';"从其他控件点击中触发?

javascript - 模板字符串 ES6

javascript - componentDidUpdate 中的 setState 将 prev 与当前状态进行比较,无法使用新数据重新呈现页面,也会出现无限循环