【问题标题】:TypeError: Cannot read property 'redirect_uris' of undefinedTypeError:无法读取未定义的属性“redirect_uris”
【发布时间】:2020-09-06 19:01:07
【问题描述】:

我想编写一个应用程序来处理我的一些以某种方式标记的 gmail 电子邮件。

示例代码 here 为我的代码提供了一个起点(我已使用 promises 而不是 async await 对其进行了重写):

'use strict';

const path = require('path');
const { google } = require('googleapis');
const { authenticate } = require('@google-cloud/local-auth');

authenticate({
    keyfilePath: path.join(__dirname, 'key.json'),
    scopes: [
        'https://www.googleapis.com/auth/gmail.readonly',
    ],
}).then(auth => {
    google.options({ auth })

    gmail.users.messages.list({
        userId: "me",
    }).then((res) => {
        console.log(res.data)
    }).catch(err => {
        console.log(err)
    })
}).catch(err => {
    console.log(err);
})

以下是我目前采取的步骤:

  • 创建了一个谷歌云项目
  • 创建了具有所有者角色的服务帐号
  • 从服务账户下载了密钥文件并复制到我的代码目录为key.json
  • 运行代码:
GOOGLE_APPLICATION_CREDENTIALS="$(pwd)/key.json" node index.js

这是我得到的错误:

TypeError: Cannot read property 'redirect_uris' of undefined
    at authenticate (/home/user/dev/gmail-processor/node_modules/@google-cloud/local-auth/build/src/index.js:46:15)
    at Object.<anonymous> (/home/user/dev/gmail-processor/index.js:7:1)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

似乎它需要带有重定向 url 的 oauth 凭据。此外,当我调用authenticate 时包含keyfilePath 时,我正在导出GOOGLE_APPLICATION_CREDENTIALS 似乎是多余的。我做错了什么,我怎样才能让这段代码成功执行?

【问题讨论】:

  • 您正在使用的库处于 beta 模式:Ref。要专门使用local-auth吗?指定here 的工作流是否可以选择?
  • 您找到解决此问题的方法了吗?我在使用 Youtube Data API 时遇到了同样的问题。

标签: javascript node.js google-cloud-platform gmail-api google-auth-library-nodejs


【解决方案1】:

我使用以下方法解决了这个问题:

const auth = new google.auth.GoogleAuth({
  keyFile: path.join(__dirname, 'key.json'),
  scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
});

代替:

const auth = await authenticate({
  keyfilePath: path.join(__dirname, 'key.json'),
  scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
});

【讨论】:

    【解决方案2】:

    在您的key.json 文件中,您必须传递您的redirect_uris

    {
      ...
      "web": {
       // put your callback here:
        "redirect_uris": ["http://localhost:3000/oauth2callback"]
      }
    }
    

    之后,它应该可以工作。不过,文档并不清楚这一点。我还在想办法。

    编辑 1

    好的,我明白了……

    如果您还没有创建 OAuth 2.0 客户端 ID,请转到您的 credentials section on Google Cloud Console,然后下载 JSON 文件。将该 JSON 文件用作您的 keys.json。它对我有用:)

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2019-08-19
      相关资源
      最近更新 更多