Google-api-nodejs-client: Undefined response after authentication

Created on 4 May 2018  路  1Comment  路  Source: googleapis/google-api-nodejs-client

Hi, I'm planning to use the gmail client but I'm stuck with authorization, I've followed the example at github.com/google/google-api-nodejs-client/tree/master/samples

I grabbed the authorization function from https://github.com/google/google-api-nodejs-client/blob/master/samples/oauth2.js#L53-L79 and the rest from gmail examples folder

I can't understand why the authorization succeed but the request return undefined, here is my code:

const {google} = require('googleapis');
const {OAuth2Client} = require('google-auth-library');
const scopes = ['https://www.googleapis.com/auth/gmail.readonly'];

// Get the keys
const keyPath = path.join(__dirname, 'client_secret.json');
let keys = { redirect_uris: ['http://localhost:3000/oauth2callback'] };
if (fs.existsSync(keyPath)) {
  keys = Object.assign(keys, require(keyPath).web);
}

function getAuthenticatedClient() {
  return new Promise((resolve, reject) => {
    // create an oAuth client to authorize the API call.  Secrets are kept in a `keys.json` file,
    // which should be downloaded from the Google Developers Console.
    const oAuth2Client = new OAuth2Client(
      keys.client_id,
      keys.client_secret,
      keys.redirect_uris[0]
    );

    // Generate the url that will be used for the consent dialog.
    const authorizeUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' ')
    });

    // 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 qs = querystring.parse(url.parse(req.url).query);
        console.log(`Code is ${qs.code}`);
        res.end('Authentication successful! Please return to the console.');
        server.close();

        // Now that we have the code, use that to acquire tokens.
        const r = await oAuth2Client.getToken(qs.code)
        // Make sure to set the credentials on the OAuth2 client.
        oAuth2Client.setCredentials(r.tokens);
        console.info('Tokens acquired.');
        resolve(oAuth2Client);
      }
    }).listen(3000, () => {
      opn(authorizeUrl);
    });
  });
}

async function main() {
  const oAuth2Client = await getAuthenticatedClient();

  const gmail = google.gmail({
    version: 'v1',
    auth: oAuth2Client
  });

  const res = await gmail.users.messages.list({ userId: 'me' });
  console.log(res);  // is undefined
};

main().catch(console.error);

I successfully authenticate, get the token, but the request to __gmail.users.messages.list({ userId: 'me' })__ returns undefined but on the API explorer is working.

I can't understand what is wrong, thanks!

Most helpful comment

OMG.. :cry: after a lot of struggling I realized that I has installed through npm the version 27.0.0 and looking at the releases changelog I see that await stuff is enabled after 28.0.0, fixing the dependency to: "googleapis": "^28.0.0" solved it..

I'm so happy I was going crazy

>All comments

OMG.. :cry: after a lot of struggling I realized that I has installed through npm the version 27.0.0 and looking at the releases changelog I see that await stuff is enabled after 28.0.0, fixing the dependency to: "googleapis": "^28.0.0" solved it..

I'm so happy I was going crazy

Was this page helpful?
0 / 5 - 0 ratings