如何从Google Cloud Functions NodeJS连接到Google Cloud Storage

时间:2019-02-17 19:18:23

标签: node.js google-cloud-storage google-cloud-functions

我有以下代码示例,该示例接收一个bufferedImage及其mimeType,然后将其上传到Google Cloud Storage。

一切正常,但由于某种原因,我的Google Cloud Function从存储API收到403错误。

我该怎么做才能使我的GC功能可以访问GC存储?

我在文档中找不到任何可以向我展示如何做的东西。

const { Storage } = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

// Lists all buckets in the current project
const buckets = storage.getBuckets();

exports.uploadImage = (bucketName, fileName, imageBuffer, mimeType) => {
  return new Promise((resolve, reject) => {

    let bucket = storage.bucket(bucketName);

    let file = bucket.file(fileName);
    file.save(imageBuffer,
        {
            metadata: { contentType: `image/${mimeType}` },
        },
        ((error) => {
            error ? reject(error) : resolve()
        })
    );
  })
}

这是我遇到的错误

  

{“代码”:403,“错误”:[{“域”:“全局”,“原因”:“禁止”,“消息”:“ directed-galaxy-221521@appspot.gserviceaccount.com不拥有对blog / e33f9c9d-65f0-4a7f-8332-29846f770e6d的访问权限。“}],”消息“:” directed-galaxy-221521@appspot.gserviceaccount.com无访问权限blog / e33f9c9d-65f0-4a7f-8332-29846f770e6d。“}

2 个答案:

答案 0 :(得分:2)

云功能(CF)由特定的服务帐户(在您的情况下为directed-galaxy-221521@appspot.gserviceaccount.com)执行。来自Runtime service account

  

在执行功能期间,Cloud Functions使用服务帐户   PROJECT_ID@appspot.gserviceaccount.com作为身份。

由于访问存储桶/文件时出现403错误,这意味着它们不能公开访问,因此您需要授予上述服务帐户必要的访问许可(至少{{1} }(错误消息中提到)),具体取决于您为存储设备选择和配置的Access Control Option

答案 1 :(得分:1)

因此,显然Google Cloud中存在一些故障。由于某些原因,除非已创建存储桶,否则不允许我对其进行写入。我将bucketName更改为现有的存储桶,并收到200条响应。 Google Cloud应该发送的是404而不是403响应。403具有误导性,因为1.我的服务确实具有存储区创建特权,并且2.该存储区从一开始就不存在。这意味着404 Not Found是适当的回复。我希望这对某人有帮助。