简体   繁体   中英

List Messages using Gmail API NodeJS authorization error

I wrote a simple code to list the messages from my gmail account. However, on I get a 401 error. My code is as below

const gmailKey = google.gmail({version: 'v1', oauth2Client});

var initialRequest = gmailKey.users.messages.list({
    'userId': 'me'
});
getPageOfMessages(initialRequest, []);

var getPageOfMessages = function(request, result) {
    request.execute(function(resp) {
        result = result.concat(resp.messages);
        var nextPageToken = resp.nextPageToken;
            if (nextPageToken) {
                request = gmail.users.messages.list({
                    'userId': 'me',
                    'pageToken': nextPageToken
                });
                getPageOfMessages(request, result);
            }else{
                callback(result);
            }
    });
};

And the error is

code: 401,
errors:
[{ domain: 'global',
   reason: 'required',
   message: 'Login Required',
   locationType: 'header',
   location: 'Authorization' }]

The oauth2Client is as below

const oauth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL
);

I used the same oauth2Client to get the access token and also have verified the same in the .credentials subsection. I also ensured that the oauth2Client initializing the gmailKey contains the appropriate credentials.

How can I resolve the gmail authorization problem?

Thanks in Advance

'Login Required',

Means exactly that you need to be authenticated in order to access a users data.

You may want to consult Authorizing Your App with Gmail or this but its drive you will have to alter it slightly Oauth2 user agent

var GoogleAuth; // Google Auth object.
function initClient() {
  gapi.client.init({
      'apiKey': 'YOUR_API_KEY',
      'clientId': 'YOUR_CLIENT_ID',
      'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
      'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
  }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);
  });
}

If you are using node you could try the node.js quickstart

If you're still having this issue, the problem with not setting the authorisation is in the first line of code you pasted:

const gmailKey = google.gmail({version: 'v1', oauth2Client});

The correct way to set oauth2Client is:

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

or

google.options({ auth: oauth2Client }); // sets globally const gmailKey = google.gmail('v1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM