Reputation: 392
I have the following function:
var submit = (event) => {
event.preventDefault();
var xhr = new XMLHttpRequest();
var url = '*removed*';
xhr.open('POST', url, true);
xhr.responseType = "json";
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({ email: this.state.email, password: this.state.password }));
console.log(xhr);
}
Everything works just fine, I get the response I expected. This is the response (short):
readyState: 4
response: {token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkI…DQxfQ.s4Py_lmVK1-Ji9F573ZFddtpdnb2qa1ETHHluG11l44"}
responseType: "json"
status: 200
statusText: "OK"
I need to grab the token contained in the "response" field for future requests. The problem is that, if I call xhr.response it says "null". No matter how I call any single element of the object returned, I can't access them.
Upvotes: 1
Views: 741
Reputation: 1593
The last time I used XMLHttpRequest, I remember it having an onreadystatechange
event that is triggered once the asynchronous call is complete, that you have to write a handler for, in order to access the response from the http call.
Further reading from the mozilla docs
submit = (event) => {
event.preventDefault();
var xhr = new XMLHttpRequest();
var url = '*removed*';
xhr.open('POST', url, true);
xhr.responseType = "json";
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
}
xhr.send(JSON.stringify({ email: this.state.email, password: this.state.password }));
}
Upvotes: 1