jgozal jgozal - 2 years ago 135
Ajax Question

Any way to make AJAX calls to Gmail API without going through JS library?

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

Is it possible to make the request using the good ol'
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)
xhr.open( "GET", "https://www.googleapis.com/gmail/v1/users/me/messages", true );

But I get a 401, even after authenticating.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download