XmlHttpRequest get callback response when request fails - javascript

I have a simple request I make to my service:
var request = new XMLHttpRequest();
request.open("OPTIONS", url, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (request.readyState != 4) {
return;
}
var authType = request.getResponseHeader("WWW-Authenticate");
makeRequest(...);
};
request.send();
}
So what I'm trying to achieve is make a call to my endpoint to see what's the authorisation type (basic or bearer) and then when I get the auth type I will make the actual request with the proper credentials.
If I make the request manually I get the 401 unauthorised which is normal but I also get the WWW-Authenticate: Basic ... in my headers. However if I do this javascript call it will just fail with 401:unauthorised but I don't get this failed response in my callback so the authType will be undefined.
I haven't used javascript before so the question is how can I get the response in the callback even if the request failed with unAuthorised ?

XMLHttpRequest has an onerror callback that you can use:
var request = new XMLHttpRequest();
...
request.onerror = function(){
if (this.status == 401) {
}
}
...
request.send();

Related

Execute a http request response in javascript

I have an http request which delivers 'JSON.stringify(data)'.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/api/hello", true);
xhr.send();
xhr.onreadystatechange = function () {
console.log(xhr.responseText);
};
How can I run the code and print the contents of data?
your code should be working, the endpoint may be the problem, check the url your trying to get into the endpoint from, then don't forget to check the readyState and the status of your request before doing nothing.
xhr.onreadystatechange = function () {
if (xhr.readState === 4 && xhr.status === 200)
{
console.log(xhr.responseText);
}
};

Writing Request Payload property on httprequest

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));

XMLHttpRequest doesn't send some headers

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?

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
});
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);

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

Categories