首页 > 解决方案 > 如何使用服务帐户凭据初始化 Google Cloud Storage NodeJS 客户端库

问题描述

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

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

然后我有这个简单的云存储上传片段:

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.jsgoogle-cloud-platformgoogle-cloud-storagegoogle-authentication

解决方案


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

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

const storage = new Storage({
  credentials: creds
});

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


推荐阅读