google-api-nodejs-client не получает подробности - PullRequest
0 голосов
/ 19 ноября 2018

Я использую google-api-nodejs-client oauth2.js, и консоль не отображает никаких ошибок, но данные профиля не извлекаются из зарегистрированных пользователей в консоли.Вот мой код, где «Привет, 2» - последняя строка, отображаемая в консоли.Может кто-нибудь указать мне неправильную часть?Я включил в каталог oauth2.keys.json.

Редактировать: Я только что обнаружил, что Hey там.3 отображается, но через очень большой промежуток времени.

 'use strict';


const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
const opn = require('opn');
const destroyer = require('server-destroy');
const {google} = require('googleapis');
const plus = google.plus('v1');
console.log("Hey there.1");

 /**
  * To use OAuth2 authentication, we need access to a a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI.  To get these credentials for your application, visit https://console.cloud.google.com/apis/credentials.
  */
 const keyPath = path.join(__dirname, 'oauth2.keys.json');
 let keys = {redirect_uris: ['']};
 if (fs.existsSync(keyPath)) {
   keys = require(keyPath).web;
 }

 /**
  * Create a new OAuth2 client with the configured keys.
  */
 const oauth2Client = new google.auth.OAuth2(
   keys.client_id,
   keys.client_secret,
   keys.redirect_uris[0]
 );

 /**
  * This is one of the many ways you can configure googleapis to use authentication credentials.
  In this method, we're setting a global reference for all APIs.
  Any other API you use here, like google.drive('v3'), will now use this auth client.
  You can also override the auth client at the service and method call levels.
  */
 google.options({auth: oauth2Client});

 /**
  * Open an http server to accept the oauth callback.
  The only request to our webserver is to /callback?code=<code>
  */
 async function authenticate(scopes) {
   return new Promise((resolve, reject) => {
     // grab the url that will be used for authorization                
     const authorizeUrl = oauth2Client.generateAuthUrl({
       access_type: 'offline',
       scope: scopes.join(' '),
     });
     console.log("Hey there.2");                                    
     const server = http
     .createServer(async (req, res) => {
        try {
            console.log("Hey there.3");
          if (req.url.indexOf('google') > -1) {
            //const qs = querystring.parse(url.parse(req.url).query);
            const qs = new url.URL(req.url).searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            //const {tokens} = await oauth2Client.getToken(qs.code);
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
            console.log("Hey there.4");
          }
         } catch (e) {
            console.log(e);
            reject(e);
         }
       })
       .listen(3000, () => {
         // open the browser to the authorize url to start the workflow
         opn(authorizeUrl, {wait: false}).then(cp => cp.unref())
         ;
       });
     destroyer(server);
   });
 }

 async function runSample() {
   // retrieve user profile
   const res = await plus.people.get({userId: 'me'});
   console.log(res.data);
   console.log("Hey there.5");
   console.log(userId);
 }

 const scopes = ['https://www.googleapis.com/auth/plus.login'];
    authenticate(scopes)
   .then(client => runSample(client))
   .catch(console.error);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...