我正在尝试使用 JavaScript
googleapis
API 读取 Google 文档文件的内容。该文件存在,我可以发送请求,但在读取内容时收到 404 错误。
重现:
Owner
角色的服务帐户json
服务帐户密钥Node.js
代码会出现 404 错误:const { google } = require("googleapis")
const auth = new google.auth.GoogleAuth({
keyFile: "<path_to_service_account_key_json_file>",
scopes: [
"https://www.googleapis.com/auth/documents"
]
})
async function getDocumentContents(documentId) {
try {
const authClient = await auth.getClient()
const docs = google.docs({ version: "v1", auth: authClient })
const response = await docs.documents.get({ documentId })
return response.data
} catch (error) {
console.error(error)
}
}
(async () => {
const documentId = "2PACX-1vRMx5YQlZNa3ra8dYYxmv-QIQ3YJe8tbI3kqcuC7lQiZm-CSEznKfN_HYNSpoXcZIV3Y_O3YoUB1ecq"
const documentContents = await getDocumentContents(documentId)
console.info(documentContents.body.content)
})()
我希望将 this file 的文件内容打印到控制台,但我收到了 404 错误。我错过了什么?
这是完整的错误消息:
GaxiosError: Requested entity was not found.
at Gaxios._request (<path>/node_modules/gaxios/build/src/gaxios.js:142:23)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async JWT.requestAsync (<path>/node_modules/google-auth-library/build/src/auth/oauth2client.js:429:18)
at async getDocumentContents (<path>/<file_name>.cjs:25:26)
at async <path>/<file_name>.cjs:36:30 {
config: {
url: 'https://docs.googleapis.com/v1/documents/2PACX-1vRMx5YQlZNa3ra8dYYxmv-QIQ3YJe8tbI3kqcuC7lQiZm-CSEznKfN_HYNSpoXcZIV3Y_O3YoUB1ecq',
method: 'GET',
apiVersion: '',
userAgentDirectives: [ [Object] ],
paramsSerializer: [Function (anonymous)],
headers: {
'x-goog-api-client': 'gdcl/7.2.0 gl-node/22.11.0',
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/7.2.0 (gzip)',
Authorization: '<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.'
},
params: {},
validateStatus: [Function (anonymous)],
retry: true,
responseType: 'unknown',
errorRedactor: [Function: defaultErrorRedactor],
retryConfig: {
currentRetryAttempt: 0,
retry: 3,
httpMethodsToRetry: [Array],
noResponseRetries: 2,
retryDelayMultiplier: 2,
timeOfFirstRequest: 1735753900182,
totalTimeout: 9007199254740991,
maxRetryDelay: 9007199254740991,
statusCodesToRetry: [Array]
}
},
response: {
config: {
url: 'https://docs.googleapis.com/v1/documents/2PACX-1vRMx5YQlZNa3ra8dYYxmv-QIQ3YJe8tbI3kqcuC7lQiZm-CSEznKfN_HYNSpoXcZIV3Y_O3YoUB1ecq',
method: 'GET',
apiVersion: '',
userAgentDirectives: [Array],
paramsSerializer: [Function (anonymous)],
headers: [Object],
params: {},
validateStatus: [Function (anonymous)],
retry: true,
responseType: 'unknown',
errorRedactor: [Function: defaultErrorRedactor]
},
data: { error: [Object] },
headers: {
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
'content-encoding': 'gzip',
'content-type': 'application/json; charset=UTF-8',
date: 'Wed, 01 Jan 2025 17:51:40 GMT',
server: 'ESF',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin, Referer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-l2-request-path': 'l2-managed-5',
'x-xss-protection': '0'
},
status: 404,
statusText: 'Not Found',
request: {
responseURL: 'https://docs.googleapis.com/v1/documents/2PACX-1vRMx5YQlZNa3ra8dYYxmv-QIQ3YJe8tbI3kqcuC7lQiZm-CSEznKfN_HYNSpoXcZIV3Y_O3YoUB1ecq'
}
},
error: undefined,
status: 404,
code: 404,
errors: [
{
message: 'Requested entity was not found.',
domain: 'global',
reason: 'notFound'
}
],
[Symbol(gaxios-gaxios-error)]: '6.7.1'
}
要访问该文件,您需要服务帐户才能访问该文件,您可以通过
从 JSON 凭证文件中查找您的服务帐户电子邮件 - 它看起来像:[电子邮件受保护]
在浏览器中打开您的 Google 文档
点击右上角“分享”按钮
将服务帐户电子邮件添加为编辑者/查看者
确保检查这些设置:
“通知他人”应取消选中 点击“发送”或“分享”确认
希望能成功