【问题标题】:How to init Google Cloud Storage NodeJS client library with service account credentials如何使用服务帐户凭据初始化 Google Cloud Storage NodeJS 客户端库
【发布时间】:2019-12-20 08:52:00
【问题描述】:

所以我有服务帐户凭据 json(作为字符串,或我的代码中的 json 对象):

{
  "type": "service_account",
  "project_id": "myproject",
  "private_key_id": "lkjshdjhskas",
  //.... etc
}

然后我有这个简单的云存储上传 sn-p:

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

const creds = {service_account_object:"creds are here"};

const storage = new Storage();

const bucketName = 'my-bucket';
const filename = 'my-file.txt';

storage.bucket(bucketName).upload(filename, {
  gzip: true,
  metadata: {
    cacheControl: 'public, max-age=31536000',
  },
});

这当然给了我一个 invalid_grant 错误:

(node:15920) UnhandledPromiseRejectionWarning: Error: invalid_grant
    at Gaxios.request (C:\Users\Yuri\Documents\Code\btests\node_modules\gaxios\build\src\gaxios.js:70:23)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:15920) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15920) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我尝试将凭据作为参数提供给Storage() 构造函数,撒谎Storage(creds) 甚至Storage(JSON.stringify(creds)),但这只会给我带来奇怪的错误。

如何使用服务帐户凭据实例化 Google 客户端库对象

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-storage google-authentication


    【解决方案1】:

    凭据数据应在您传递给构造函数的StorageOptions 对象的credentials 属性中传递:

    const creds = {
      "type": "service_account",
      "project_id": "myproject",
      "private_key_id": "lkjshdjhskas",
      //.... etc
    }
    
    const storage = new Storage({
      credentials: creds
    });
    

    一定要熟悉链接的 API 文档,因为它们会解释如何使用 API。

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      相关资源
      最近更新 更多