0

A simple guide to making a GET request to get a user's messages through Gmail API can be found here.

But the way we are instructed to do the request is in the following manner:

function getMessage(userId, messageId, callback) {
  var request = gapi.client.gmail.users.messages.get({
    'userId': userId,
    'id': messageId
  });
  request.execute(callback);
}

Is it possible to make the request using the good ol' XMLHttpRequest object on the client side? If so what parameters should be passed into the call?

I have tried this:

var getMessages = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { 
   if (xhr.readyState == 4 && xhr.status == 200)
      console.log(xhr.responseText);
   }
xhr.open( "GET", "https://www.googleapis.com/gmail/v1/users/me/messages", true );
xhr.send();
 }

But I get a 401, even after authenticating.

jgozal
  • 1,480
  • 6
  • 22
  • 43
  • I found this question which addresses a similar issue but with jquery: http://stackoverflow.com/questions/25334746/401-unauthorised-error-when-using-jquerys-get-and-gmail-api. So I added `xhr.setRequestHeader("authorization", userToken.access_token);` to my code but still getting a 401 – jgozal May 19 '16 at 03:57

1 Answers1

0

As it states in this answer, you should pass the access token as a query parameter with the name access_token, or prefix the authorization header value with "Bearer", like so:

xhr.setRequestHeader("authorization", "Bearer " + userToken.access_token);
Community
  • 1
  • 1
hakas
  • 125
  • 1
  • 6
  • ugh! I was so close! I never really understood why the word "Bearer" had to be included and what it meant so I'll read on it now so I don't forget again. Thank you! – jgozal May 19 '16 at 13:39