I am getting the raw data of the drafted from Gmail API "get" method and sending it using Gmail API "send" method.
'var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/id?
format=raw&alt=json&access_token=' + token;
url = url.replace("id", emailId);
var x = new XMLHttpRequest();
x.open('GET', url , true);
x.send();
x.onload = function() {
var jsonRes = JSON.parse(x.response);
sendEmail(jsonRes.raw);
}
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json&access_token=' + token;
params = "raw=" + raw;
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}`
I am getting 401 status.
If I am sending this raw data from API page itself, then it is sent successfully. Therefore the raw data is correct.
I am missing something while sending the email. Please help!
A 401 error means "invalid credentials", most likely because your token has expired or isn't valid.
The Google API explorer and Google Javascript libraries take care of the token for you (generally), but if you're calling the service endpoints directly with XMLHttpRequest(), you'll have to manage the token yourself.
If you want to go that route, here are the details you have to implement: https://developers.google.com/identity/protocols/OAuth2
You can try things out in the "Oauth2 playground": https://developers.google.com/oauthplayground/
Thank you for all responses.
I sent the email using the following code-
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send';
var params = JSON.stringify({'raw': raw});
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}
}
There were two mistakes I rectified-
1. The token was sent in URL as well as header. It should be sent only in header.
2. The param raw was sent as String but it should be sent as a JSON object.
Related
I've now spent some time trying to get the JavaScript below working in my API (c#).
I run perfectly in JavaScript, but I get access denied as a response in my c# code.
JS :
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
document.getElementById('KundeListing').innerHTML = this.responseText;
console.log(this.responseText);
}
});
xhr.open("GET", "https://plus.dnb.com/v1/search/typeahead?searchTerm=Wal&countryISOAlpha2Code=US");
xhr.setRequestHeader("Authorization", "Bearer " + Token);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.withCredentials = false;
xhr.send();
But When trying usingRestSharp; I am getting errors
'You are not currently authorized to access this product'
public string Get(string Token)
{
var client = new RestSharp.RestClient("https://plus.dnb.com/v1/search/typeahead?searchTerm=Wal&countryISOAlpha2Code=US");
var request = new RestRequest(Method.GET)
{
UseDefaultCredentials = true
};
request.AddHeader("accept", "application/json");
request.AddHeader("authorization", "Bearer " + Token);
IRestResponse response = client.Execute(request);
return response.ToString();
}
We have a server which is implemented by python flask and it's RESTful. Since it is RESTful, we must develop the front-end pages using APIs.
The problem is, our server uses flask's built-in Login_manager and session modules to manage client sessions. When I try to send requests to #login-required APIs, the server won't allow me. Based on my searches, I have to somehow send front-end's session cookie to the server, along with my requests. So how should I do this (If this is the solution)? And what should I add to my javascript login and API fetch codes?
JS login :
var request = new XMLHttpRequest();
var url = 'http://127.0.0.1:5000/api/login';
var user = {
'email': email,
'password': password
};
request.open('POST', url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
var resp = JSON.parse(this.response);
if (resp.status === "OK") {
sessionStorage.setItem('user', JSON.stringify(resp.user));
document.cookie = "user_id="+resp.user.id;
window.location.replace('app.html');
} else {
alert("User info not correct");
}
} else {
alert("Request not made");
}
}
request.send(JSON.stringify(user));
And then, script isn't working because the /showApps API is #login-required :
var request = new XMLHttpRequest();
var url = 'http://127.0.0.1:5000/api/showApps';
request.open('GET', url, true);
request.onload = function(e) {
//manage data
}
request.send();
I am trying to develop a browser extension that will help people to some stuff way easier.
One of the things that I need to do is sending couple of http requests.
I need to recreate requests that site makes when doing certain things.
Now site uses Request Payload which is my first time using(used form data),therefore I don't know how to make Request Payload same as when site sends request.
var request = new XMLHttpRequest(),
url = 'https://www.hidden.com/api/v1/tipuser/',
data = 'steam_64=76561198364912967&tip_asset_ids=[]&tip_balance=0',
token ='...';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'text/plain');
request.setRequestHeader('authorization', token);
request.send(data);
This is my code and after sending it you can see how my Request Payload looks.
I have been having difficulties for days now and I searched online but couldn't find solution to this.I know that I just have to write it differently .
This is site's request
This is my request
Cheers!
Could you try sending your request as application/json and build your data object like in the example below?
Your Content-type request header should be application/json
var request = new XMLHttpRequest(),
url = 'https://jsonplaceholder.typicode.com/posts/',
data = {
steam_64: '76561198364912967',
tip_asset_ids: [],
tip_balance: 0,
token: '',
};
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json');
request.setRequestHeader('authorization', data.token);
request.send(JSON.stringify(data));
I am having some trouble getting an access token from a site for a web application. The response to the following is
"{"error":"invalid_request","error_description":"The grant type was not specified in the request"}".
I have specified the grant type below but it seems I have not formatted the request correctly.
Any suggestions?
var getToken = new XMLHttpRequest();
getToken.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
getToken.open("POST", "https://api2.libcal.com/1.1/oauth/token", true);
getToken.send('grant_type=client_credentials','client_id=XXX', 'client_secret=XXXXXXXXXXXXXXXXXXXX');
As you are doing a Post Request to get an access token , the parameters should be send in the body (JSON) like below : (I tested ,it works fine )
// form data for the post request
var data = {
"grant_type":"client_credentials",
"client_id": "XXX",
"client_secret": "XXXXXXXXXXXXXXXXXXXX"
};
// construct an HTTP request
var getToken= new XMLHttpRequest();
getToken.open("POST", "https://api2.libcal.com/1.1/oauth/token", true);
getToken.setRequestHeader('Content-Type', 'application/json');
// send the collected data as JSON
getToken.send(JSON.stringify(data));
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.
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);