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();
Related
I'm currently integrating Base CRM API on my App. I tried making an AJAX call for the API. I have my access token on the variable "token", just replaced it with some text on the code sample below:
var request;
var token = "token"
request = new XMLHttpRequest();
request.open("GET",'https://api.getbase.com/v2/accounts/self', true);
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('Authorization','Bearer ' + token );
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200){
alert(request.response);
}
}
request.send();
After I run this, I'm getting a "404" error on Base's "https://api.getbase.com/v2/accounts/self" endpoint.
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.
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));
The title explains my problem clearly. I am testing the AJAX requests of my application but I cannot send some headers, for example Authorization header.
For testing I use this endpoint to echo me the headers I sent. Here is my javascript code:
var loadDoc = function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(JSON.parse(this.responseText));
};
}
xhttp.open("GET", "http://headers.jsontest.com/", true);
xhttp.setRequestHeader("Authorization", "JWT token");
xhttp.send();
}
I can send the exact same request with python's requests module. But I can't send it with XMLHttpRequest. XMLHttpRequest can send the Content-Type header and the server echoes me the headers but not Authorization.
What is going on here?