获取被 CORS 阻止。获取谷歌云功能时,航班请求未通过访问控制检查

问题描述 投票:0回答:1

我想从我的 chrome 网络浏览器(从开发控制台)将数据发送到谷歌云功能。但是我被卡住了。已经尝试了我在谷歌甚至 ChatGPT 上能找到的所有东西。

我不断收到错误: 从来源“https://chat.openai.com”获取“云功能链接”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“Access-Control-Allow-Origin” ' 标头存在于所请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

我在浏览器中注入的javascript:

var data = { key: 'value' }; 
fetch('https://google cloud function link', {
  method: 'POST',
  mode: 'cors',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

编辑::已解决 云函数的最新 Python 代码,感谢 DominicT! 自从上次我也尝试了下面的代码但它没有工作以来无法查明错误:

import functions_framework

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

    # 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': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('test', 204, headers)

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

    from github import Github

    # First create a Github instance:
    import os
    GIT_TOKEN = os.environ["GIT_TOKEN"]

    # using an access token
    g = Github(GIT_TOKEN)

    # Then play with your Github objects:
    for repo in g.get_user().get_repos():
        if repo.name == "chat_gpt_results":
            repo.create_file("test_file_test_funct.txt", "init commit", "file_content ------ ")

    return (repo.name, 200, headers)
google-cloud-functions cors fetch-api
1个回答
0
投票

这里好像是ChatGPT域不允许跨源请求。

您使用错误的域来访问 OpenAPI API。您可以在这里找到文档:https://platform.openai.com/docs/introduction.

如果您仍想从浏览器向该域发出请求,您应该创建一个 Google 函数来充当您请求的代理。

© www.soinside.com 2019 - 2024. All rights reserved.