node.js - 如何使用服务帐户凭据初始化 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 客户端库对象?
解决方案
凭据数据应在您传递给构造函数的StorageOptions对象的credentials
属性中传递:
const creds = {
"type": "service_account",
"project_id": "myproject",
"private_key_id": "lkjshdjhskas",
//.... etc
}
const storage = new Storage({
credentials: creds
});
一定要熟悉链接的 API 文档,因为它们会解释如何使用 API。
推荐阅读
- actionscript-3 - RTMP 共享对象
- c++ - 当我使用c ++ builder时如何在输入完成后自动跳转到下一个“TEdit”
- msbuild - 是否允许重新分发 Microsoft Build 工具?
- linux - 如何使用日志处理程序将信号记录到应用程序信号?
- javascript - Firebase“需要最近登录”
- javascript - 在 React setState 函数中使用 e.target.value 的问题
- python - 等号处的无效语法
- swift - 在 Apple Watch 上获取 RSSI
- sql - 如何在列上创建完全不区分大小写的检查约束
- django - Nginx 服务器上的 Django 没有反向匹配