chu*_*Dub 4 gmail google-api node.js
我第一次尝试使用 google API,当我尝试向 gmail API 发出请求时,出现“前提条件检查失败”错误。我使用的是服务帐户授权,而不是 Oauth2 用户同意。我尝试过的事情:
这是来自 Node 客户端库的改编示例,但该示例未使用服务帐户身份验证,因此我无法直接使用该示例。
const path = require('path');
const {google} = require('googleapis');
const gmail = google.gmail('v1');
async function runSample() {
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: path.resolve(__dirname, 'google-key.json'),
scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
});
google.options({auth});
const res = await gmail.users.messages.list({userId: 'me'}); // have tried with my gsuite email address as well
console.log(res.data);
return res.data;
}
if (module === require.main) {
runSample().catch(console.error);
}
module.exports = runSample;Run Code Online (Sandbox Code Playgroud)
返回错误消息:Error: Precondition check failed.
在暗网搜索了很久之后,我发现了一个github 问题的链接,该问题描述了如何使用 JWT 身份验证作为服务进行身份验证。
这是我试图完成的工作版本:
const path = require('path');
const {google} = require('googleapis');
async getMessageList(userId, qty) {
const JWT = google.auth.JWT;
const authClient = new JWT({
keyFile: path.resolve(__dirname, 'google-key.json'),
scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
subject: 'admin@example.com' // google admin email address to impersonate
});
await authClient.authorize(); // once authorized, can do whatever you want
const gmail = google.gmail({
auth: authClient,
version: 'v1'
});
const response = await gmail.users.messages.list({
includeSpamTrash: false,
maxResults: qty,
q: "",
userId: userId
});
// the data object includes a "messages" array of message data
return response.data;
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4855 次 |
| 最近记录: |