PenPen
PenPen

Reputation: 58

Post request body google api

I am trying to create a draft in gmail using google api.

After authorization I am having trouble using POST to send request body. Here is a simplified version of my code.

var token = hash[1].split('=')[1]; // getting token
var body = "some text";
var base64message = Base64.encode(body); //uses base64 library to encode message
var params ={
    "message": {
        "raw": base64message
    }
}
var request = new XMLHttpRequest();
request.onload = function(){
    console.log(this.responseText); // parseError
}

request.open('POST','https://www.googleapis.com/gmail/v1/users/me/drafts?access_token='+token,true);
request.send(JSON.stringify(params));

Solved forgot this:

request.setRequestHeader('Content-Type', 'application/json');

Upvotes: 0

Views: 1014

Answers (1)

Luka Čelebić
Luka Čelebić

Reputation: 1093

Instead of:

request.onload = function(){
    console.log(this.responseText); // parseError
}

Use onreadystatechange after which you ask if(this.readyState == 4 && this.status == 200){.

  1. this.readyState == 4 means that the request is finished or processed
  2. this.status == 200 means that it also succeeded.

.onload was added in XMLHttpRequest 2 whereas onreadystatechange has been around since the original spec. .onload is equal only to this.readyState == 4.

So your code will look like this:

var token = hash[1].split('=')[1]; // getting token
var body = "some text";
var base64message = Base64.encode(body); //uses base64 library to encode message
var params ={
    "message": {
        "raw": base64message
    }
};

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
    }
};

request.open('POST','https://www.googleapis.com/gmail/v1/users/me/drafts?access_token='+token,true);
request.send(JSON.stringify(params));

Upvotes: 1

Related Questions