使用Node.js结合googleapis获取谷歌认证用户邮箱触发API权限报错
接口失效根因与修正方案
你当前调用的plus.people.get属于2021年已全量下线的Google+ Legacy API,报错中提及的legacypeople.googleapis.com就是这个废弃接口的服务域名。目前谷歌公开文档中仍保留该接口的历史记载,是因为归档类内容没有做全量下线提醒,不代表接口仍可正常使用。即便你按照报错提示跳转控制台尝试“启用”该API,这个服务本身已经没有可用的后端支撑,无论怎么配置都无法调用成功,这也是你网页加载异常的核心原因。
下面是可直接落地的修正步骤:
- 移除所有旧Google+ v1 API的初始化与调用逻辑,改用谷歌现行的官方替代接口People API v1,该接口完整承接了原Google+接口的用户信息查询能力。
- 替换错误代码为以下可运行的逻辑:
if (!req.body.token) return res.status(500).json({ type: 'error', message: 'No access token provided.' }) const OAuth2 = google.auth.OAuth2 const oauth2Client = new google.auth.OAuth2(keys.client_id, keys.client_secret) // 移除旧的plus服务初始化代码:const plus = google.plus('v1') // 替换为People API初始化 const people = google.people('v1') oauth2Client.setCredentials({ access_token: req.body.token }) // 替换原plus.people.get的调用逻辑 people.people.get({ resourceName: 'people/me', personFields: 'emailAddresses,names,photos', auth: oauth2Client }, (error, response) => { // 修正原代码缺少大括号的语法错误:原if块未加{}导致return被全局捕获 if (error) { console.log(error) return res.status(500).json({ type: 'error', error }) } // 适配新接口的邮箱字段取值路径 const emails = (response.data?.emailAddresses || []).map(item => item.value) }) - 控制台配置调整:到对应的谷歌云项目中,启用正式版的
People API,不要操作报错链接指向的Legacy People API入口——该入口对应的服务已永久关停,无实际可用能力。 - 接口权限注意:确认你获取access token时申请的作用域包含
https://www.googleapis.com/auth/userinfo.email、https://www.googleapis.com/auth/userinfo.profile,否则即使接口调用逻辑正确,也会因为权限不足无法读取用户信息。
内容的提问来源于stack exchange,提问作者Alejandro Nieto
相关产品推荐
相关产品推荐

