首页 > 解决方案 > TypeError: key 必须是一个字符串、一个缓冲区或一个在 typeError 中存在 GCP 文件的对象

问题描述

我试图简单地测试我们的谷歌云平台(GCP)存储上是否存在文件。我在 express js 服务器上使用 GCP 存储桶。下面本质上是一个非常简单的示例,复制自https://googleapis.dev/nodejs/storage/latest/File.html#exists

编辑:这就是我验证 GCP 密钥的方式:

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

const storage = new Storage({
    projectId: 'my-cloud',
    keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,
});
const bucketName = 'my-ci';

(稍作改动,我意识到你应该回来data[0]

const bucket = storage.bucket(bucketName);
const file = bucket.file(path);
const exists = await file.exists().then(data => {
    return data
})

但是当我尝试运行它时,我得到了错误:

[nodemon] starting `node --inspect server/server.js`
Debugger listening on ws://127.0.0.1:9229/9a677766-4a93-4499-b57c-55f5f05096d7
For help, see: https://nodejs.org/en/docs/inspector
Server listening on port 4000!
/opt/node_modules/jwa/index.js:115
return new TypeError(errMsg);
^

TypeError: key must be a string, a buffer or an object
at typeError (/opt/node_modules/jwa/index.js:115:10)
at checkIsPrivateKey (/opt/node_modules/jwa/index.js:61:9)
at Object.sign (/opt/node_modules/jwa/index.js:147:5)
at Object.jwsSign [as sign] (/opt/node_modules/jws/lib/sign-stream.js:32:24)
at JWTAccess.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/jwtaccess.js:87:31)
at JWT.getRequestMetadataAsync (/opt/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:51)
at JWT.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/oauth2client.js:238:37)
at GoogleAuth.authorizeRequest (/opt/node_modules/google-auth-library/build/src/auth/googleauth.js:593:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

由于错误消息没有给出有用的回溯,我自己做了一些挖掘。通过console.log到处放置语句,我将范围缩小到行

const exists = await file.exists().then(data => {
    return data
})

并尝试了各种方法,从删除.then(...)子句到删除await(在承诺解决之前确实有效)。这些似乎都没有奏效。

这可能是什么潜在原因?

标签: javascriptnode.jsexpressgoogle-cloud-platformnodemon

解决方案


最终弄明白了——这是因为 GCP 密钥是旧版本的密钥。如果您收到上述错误,请尝试检查您的密钥是否正确。


推荐阅读