Google Docs API 是 Google 提供的一组 RESTful 接口,允许开发者以编程方式访问和操作 Google Docs 文档。请求文档列表是常见的操作之一。
400 错误表示服务器无法理解或处理客户端请求,通常由以下原因导致:
确保正确获取和使用访问令牌:
// 示例:使用 Google API 客户端库进行认证
const {google} = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFile: 'credentials.json',
scopes: ['https://www.googleapis.com/auth/documents.readonly'],
});
// 获取认证客户端
const authClient = await auth.getClient();
// 创建 Google Docs API 实例
const docs = google.docs({
version: 'v1',
auth: authClient
});
正确的文档列表请求示例:
// 获取文档列表的正确方式
const drive = google.drive({version: 'v3', auth: authClient});
drive.files.list({
q: "mimeType='application/vnd.google-apps.document'",
fields: 'files(id, name)',
}, (err, res) => {
if (err) {
console.error('The API returned an error: ' + err);
return;
}
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.forEach((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
});
确保请求的 OAuth 范围包含:
https://www.googleapis.com/auth/drive.metadata.readonly
(仅读取元数据)https://www.googleapis.com/auth/drive.readonly
(读取内容和元数据)确保请求包含正确的头信息:
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
使用 Google OAuth Playground 测试您的请求:
fields
参数指定了错误的字段通过以上步骤,您应该能够解决 400 Bad Request 错误并成功获取 Google Docs 文档列表。
没有搜到相关的沙龙