Node.js调用Google Admin Api报native promise missing错误求助
报错原因
该报错来自googleapis依赖的node-fetch库,当前运行环境无法检测到可用的原生Promise实现。
修复步骤
步骤1:注入Promise实现
你可以选择原生Promise或者第三方Promise库两种方案:
方案A:使用原生Promise(适配Node.js 4.x及以上版本)
在代码最顶部添加以下内容:
const fetch = require('node-fetch'); fetch.Promise = Promise;
方案B:使用bluebird(适配低版本Node.js)
- 先安装bluebird依赖:
npm install bluebird - 在代码最顶部添加以下内容:
const Promise = require('bluebird'); const fetch = require('node-fetch'); fetch.Promise = Promise; global.Promise = Promise;
步骤2:修复请求与身份验证参数(必做,否则后续会报权限/身份错误)
- 使用服务账号调用Google Admin API时,必须先配置全域权限委派,同时在初始化JWT客户端时指定要模拟的Workspace管理员账号
- 你原有代码初始化admin实例时没有传入已授权的auth对象,会导致请求无身份凭证报错
修改对应部分代码即可:
// JWT实例化部分 const jwtClient = new google.auth.JWT( key.client_email, null, key.private_key, SCOPES, 'admin@你的企业域名.com' // 替换为你Google Workspace下拥有超级管理员权限的用户邮箱 ); // admin实例初始化部分 let admin = google.admin({ version: 'directory_v1', auth });
可选优化:升级依赖版本
如果上述操作后仍有问题,可将googleapis升级到最新版本:npm update googleapis
修复后完整代码示例
require('../global') // 新增注入Promise逻辑 const fetch = require('node-fetch'); fetch.Promise = Promise; const fs = require('fs'); const {google} = require('googleapis'); const KEYFILE = global.service_account; const SCOPES = global.scopes; (async function run() { async function readPrivateKey() { const content = fs.readFileSync(KEYFILE); return JSON.parse(content.toString()); } async function authenticate(key) { const jwtClient = new google.auth.JWT( key.client_email, null, key.private_key, SCOPES, 'admin@你的企业域名.com' // 替换为实际管理员邮箱 ); await jwtClient.authorize(); return jwtClient; } async function createEvent(auth) { let admin = google.admin({ version: 'directory_v1', auth }); await admin.users.list({ customer:'my_customer', maxResults: 500 }); } // MAIN try { const key = await readPrivateKey(); console.log(key) const auth = await authenticate(key); await createEvent(auth); } catch (e) { console.log('Error: ' + e); } })();
内容的提问来源于stack exchange,提问作者Daniil Lesnikov
相关产品推荐
相关产品推荐

