如何使用云函数在 Firebase Cloud Storage 中创建文档

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

我创建了一个Python云函数来在Cloud Storage中创建新文档。它与 firebase 模拟器配合良好:start,但在尝试从我的应用程序调用它时出现错误:

cloud-function.ts:20 Error executing cloud function upload_html_page FirebaseError: unauthenticated

我已将安全规则设置为允许在 Firebase Cloud Storage 中读取、写入:true。

我的云功能是:

@https_fn.on_request()
def upload_html_page(req: https_fn.Request) -> https_fn.Response:
    """Store an entire recorded HTML page."""
    try:
        # Expecting the HTML content to be provided in the request body
        data = req.get_json().get('data', {})
        print(f"Received data: {data}")  # Log received data

        html_content = data.get("htmlAsString")
        documentId = data.get('documentId')
        actionId = data.get('actionId')
        eventId = data.get('eventId')

        storage_client = gcs_storage.Client()

        # Reference to your bucket
        bucket = storage_client.bucket('***SECRET FOR STACK OVERFLOW***')

        # Create a new blob and upload the file's content.
        blob = bucket.blob(documentId + "/" + eventId + "_" + actionId)

        # Upload the file to Firebase Storage
        blob.upload_from_string(html_content)

        return https_fn.Response(status=200)
    except Exception as e:
        return https_fn.Response(f"Error processing HTML content: {str(e)}", status=500)

我用打字稿来称呼它:

import { getApp } from './get-app';
import { getFunctions, httpsCallable } from 'firebase/functions';

const functions = getFunctions(getApp());
const payload: { [key: string]: any } = {};
            payload["htmlAsString"] = response.htmlAsString;
            payload["documentId"] = documentId;
            payload["actionId"] = actionId;
            payload["eventId"] = eventId;
const cloudFunction = httpsCallable(functions, "upload_html_page");
    try {
        const result = await cloudFunction(payload);
        return result.data;
    } catch (ex) {
        console.error("Error executing cloud function", name, ex);
        return null;
    }

当我拨打电话时,我已连接到应用程序中的 FireBase 帐户。

有什么我必须在 Firebase 控制台中配置的吗?

javascript python typescript firebase google-cloud-storage
1个回答
0
投票

您混淆了 callableHTTP 类型函数。 您的云函数是一个普通的 HTTP 类型函数,带有

@https_fn.on_request()
注释,但您的客户端代码正在尝试调用可调用函数。 这两种类型的功能互不兼容。

请参阅:Callable Cloud Functions 与 HTTP 函数相比如何?

您要么需要将您的函数重写为带有

@https_fn.on_request()
注释的可调用类型函数(请注意,它具有不同的 API,具有不同的返回结果),或者您需要使用普通的 HTTP 库从客户端调用您的函数.

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