[英]Post request body google api
I am trying to create a draft in gmail using google api. 我正在尝试使用Google API在Gmail中创建草稿。
After authorization I am having trouble using POST to send request body. 授权后,我无法使用POST发送请求正文。 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'); request.setRequestHeader('Content-Type','application / json');
Instead of: 代替:
request.onload = function(){
console.log(this.responseText); // parseError
}
Use onreadystatechange
after which you ask if(this.readyState == 4 && this.status == 200){
. 使用
onreadystatechange
,然后询问if(this.readyState == 4 && this.status == 200){
。
this.readyState == 4
means that the request is finished or processed this.readyState == 4
表示请求已完成或已处理 this.status == 200
means that it also succeeded. this.status == 200
表示它也成功。 .onload
was added in XMLHttpRequest 2 whereas onreadystatechange
has been around since the original spec. .onload
是在XMLHttpRequest 2中添加的,而onreadystatechange
自原始规范以来就已经存在。 .onload
is equal only to this.readyState == 4
. .onload
仅等于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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.