如何使用服务帐户凭据初始化 Google Cloud Storage NodeJS 客户端库

MeL*_*ght 2 google-authentication node.js google-cloud-storage google-cloud-platform

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

{
  "type": "service_account",
  "project_id": "myproject",
  "private_key_id": "lkjshdjhskas",
  //.... etc
}
Run Code Online (Sandbox Code Playgroud)

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

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',
  },
});
Run Code Online (Sandbox Code Playgroud)

这给了我一个 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.
Run Code Online (Sandbox Code Playgroud)

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

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

Dou*_*son 7

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

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

const storage = new Storage({
  credentials: creds
});
Run Code Online (Sandbox Code Playgroud)

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