无法通过people.connections.list获得回复

时间:2018-03-15 16:10:47

标签: node.js google-api-nodejs-client google-people

⚠️我忘记了主线程中的OAuth2Client,因此应用程序在执行回调之前终止了。 此代码示例就像魅力一样

以下是googleapis nodejs client的代码,我遇到了以下问题:

首先,我想使用nodejs应用程序获取一个用户的联系人列表

设置OAuth2Client

所以我使用以下代码设置const { client_id: CLIENT_ID, client_secret: CLIENT_SECRET } = require("./keys.json"); const REDIRECT_URL = "http://localhost:3000/oauth2callback"; const oAuth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

function getGoogleCode() {
  return new Promise((resolve, reject) => {
    // Open an http server to accept the oauth callback. In this simple example, the
    // only request to our webserver is to /oauth2callback?code=<code>
    const server = http
      .createServer(async (req, res) => {
        if (req.url.indexOf("/oauth2callback") > -1) {
          // acquire the code from the querystring, and close the web server.
          const { code } = querystring.parse(url.parse(req.url).query);
          res.end(
            `Authentication successful! Please return to the console. [code: ${code}]`
          );
          server.close();
          resolve(code);
        }

        reject(new Error("oops", req, res));
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        // Generate the url that will be used for the consent dialog.
        const authorizeUrl = oAuth2Client.generateAuthUrl({
          access_type: "offline",
          scope: ["https://www.googleapis.com/auth/contacts.readonly"]
        });
        opn(authorizeUrl);
      });
  });
}

然后,使用临时服务器,我使用用户的凭据要求令牌:

const code = await getGoogleCode();
const { tokens } = await oAuth2Client.getToken(code);
oAuth2Client.setCredentials(tokens);

然后我完成了设置我的客户端:

const personFields = ["emailAddresses", "names"];
const url = `https://people.googleapis.com/v1/people/me/connections?personFields=${personFields.join(
  ","
)}`;
const res = await oAuth2Client.request({ url });
console.log(chalk.gray(JSON.stringify(res.data.connections, null, 2)));

当一切都很好

我设法通过低级API获得响应:

const personFields = ["emailAddresses", "names"];
people.people.connections.list(
  { resourceName: "people/me", personFields },
  (res, err) => {
    console.log("error: ", err);
    console.log("res1: ", res);
  }
);

一切都像魅力一样,但是,我想使用同一个库中的高级API

google.people API

API Explorer所述,我构建了以下代码:

res1

没有错误,没有process.exit(0),没有。

⚠️我忘记了主线程中的{{1}},因此应用程序在执行回调之前终止了。 此代码示例就像魅力一样

1 个答案:

答案 0 :(得分:0)

不确定为什么你没有登录。但是你可能应该在回调中返回res,否则在回调上调用await将返回undefined

另请务必在personFields来电中设置people.people.connections.list