使用云函数时的getSignedUrl

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

我正在尝试获取图像 url,以便我可以将其作为

src
在我的 html 中传递。我创建了函数并想发送 url 作为响应。我尝试了以下方法,但我不断得到

错误:如果没有

client_email
,则无法签署数据。

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

export const getPicURL = functions.https.onRequest(
    (request, response) => {
        const storageBucket = admin
            .storage()
            .bucket('gs://my-app.appspot.com');

        const fileName = 'my-app/pic1.jpg';
        const tomorrow = new Date(
            new Date().getTime() + 24 * 60 * 60 * 1000
        );

        const signedURL = storageBucket
            .file(fileName)
            .getSignedUrl({ action: 'read', expires: tomorrow });

        signedURL
            .then((data) => {
                response.send(data[0]);
            })
            .catch((err) => {
                console.log('My Error', err);
                response.sendStatus(500).send(err);
            });
    }
);

我觉得我缺少配置步骤,但我不知道在哪里添加这些属性

firebase google-cloud-functions google-cloud-storage
2个回答
5
投票

我遇到的问题是服务帐户。我没有使用正确的配置初始化应用程序。我可以在 https://console.firebase.google.com/ >> 项目 >> 设置 >> 服务帐户 >> Firebase Admin SDK 中找到详细信息

我们需要执行以下操作,而不仅仅是

admin.initializeApp();

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://my-app.firebaseio.com"
});

0
投票

当使用 firebase function:shell 在本地运行此方法时,使用项目 id 和 key.json 的路径初始化存储对象为我解决了这个问题。我们必须像这样初始化存储

var storage = new Storage({
  projectId: "project id",
  keyFilename:"service-account-key.json"
});

然后您可以使用以下示例生成登录网址

export const getPicUrl = functions.https.onCall(async (request) => {
  try {
    const options : GetSignedUrlConfig = {
      version: 'v4', // Use version 4 signing process
      action: "write", // Specify the action (read, write, delete, etc.)
      expires: Date.now() + expirationSeconds * 1000, // Expiration time in milliseconds
    };

    // Generate the signed URL
    const [signedUrl] = await storage.bucket(bucketName).file(fileName).getSignedUrl(options);

    console.log('Signed URL:', signedUrl);
  } catch (error) {
    console.error('Error:', error);
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.