【问题标题】:CORS error in firebase python cloud function [closed]firebase python云函数中的CORS错误[关闭]
【发布时间】:2020-08-25 23:21:24
【问题描述】:

我的 firebase python HTTP 云函数不断抛出 CORS 错误:

Access to fetch at 'https://<project>.cloudfunctions.net/<fn_name>' 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.

即使我正在处理预检请求:

def get_user_db_exist(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """

    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 ('', 204, headers)
    headers = {
        'Access-Control-Allow-Origin': '*'
    }
    print(request)
    return (json.dumps({ 'status': 'sucess' }), 200, headers)

我尝试将 Access-Control-Allow-Methods 设置为 'GET''POST''GET, POST' 无济于事(来自前端的请求是 POST 请求)。

我还尝试创建一个可用的现有函数的副本。虽然现有功能有效,但新创建的副本引发了 CORS 错误。

google cloud function python CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource.https://cloud.google.com/functions/docs/writing/http#functions_http_cors-python 的说明无效。

前端是一个使用 firebase sdk 版本 7.14.3 的 React 应用程序。 (它也不适用于v7.14.2)。

【问题讨论】:

  • 您确定您的 OPTIONS 代码正在被使用吗?您可以在选项请求中添加一些调试或设置自定义标头以检查您是否在 React 中获得它?没有使用 Flask 的经验,但发现此注释:从 Flask 0.6 开始,OPTIONS 被隐式添加并由标准请求处理处理
  • 如果你为你的 Flask 应用发布路由配置也许会有所帮助。
  • 如果我错了,请纠正我,但不是在预检请求中使用了 OPTIONS 方法(查看 HTTP 资源允许哪些选项)?我也没有用flask app,前端是React,数据库是firebase,所以用了python云函数

标签: python firebase cors google-cloud-functions


【解决方案1】:

您没有正确设置响应标头。改变

return json.dumps({ 'status': 'sucess' }, 200, headers)

收件人:

return (json.dumps({'status': 'sucess'}), 200, headers)

完整代码:

from flask import json


def cors_enabled_function(request):
    # Set CORS headers for preflight requests
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600',
        }
        return ('', 204, headers)

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

    return (json.dumps({'status': 'sucess'}), 200, headers)

这是在http://localhost:5000上运行的前端应用:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your front end app</title>
  </head>
  <body>
    <script>
      window.onload = async function () {
        const endpoint = 'https://us-central1-xxxxx-218808.cloudfunctions.net/cors_enabled_function';
        const res = await fetch(endpoint, { method: 'POST' }).then((res) => res.json());

        console.log('res:', res);
      };
    </script>
  </body>
</html>

console.log 的输出:res: {status: "sucess"}

检查浏览器的响应头:

access-control-allow-origin: *
alt-svc: h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,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,quic=":443"; ma=2592000; v="46,43"
cache-control: private
content-encoding: gzip
content-length: 40
content-type: text/html; charset=utf-8
date: Wed, 13 May 2020 09:05:21 GMT
function-execution-id: maluigz9ytxx
server: Google Frontend
status: 200
x-cloud-trace-context: 853d11ceef85ec4a231d45dd59f7377e;o=1

access-control-allow-origin: * 标头设置成功。

【讨论】:

  • 谢谢。我在将代码复制到编辑器时犯了一个错误。我部署的云功能具有正确的语法。问题的原因显然是不允许未经授权的访问的权限错误。
猜你喜欢
  • 2020-07-07
  • 2020-04-27
  • 2018-07-27
  • 2020-08-16
  • 2018-05-15
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
相关资源
最近更新 更多