Skip to content
Advertisement

Read response from HttpRequest in JavaScript

First, you can ignore that this is sending credentials in an unsafe manner. I’m supposed to handle that after.

My problem is with reading the ‘response’ or ‘responseText’ from a HttpRequest to an API. I can see in the console the request is succesful and the response I want is there, but I am not able to retrieve it. I must be missing something basic probably.

This is the response as I can see in the console:

Chrome console

I can see the “web.html” that I want to retrieve and also the status 200. But the console log is empty. This is how I am trying to do this.

JavaScript

For some more details, this is calling my Api in .NET which returns 401 Unauthorized if the credentials are wrong, and 200 OK with a string as in Ok(“web.html”) if the credentials are correct.

Thank you.

I tried printing the request and trying with all its attributes I could think of. I can see the request is working and the server is sending the response I want, but I am clueless as how to retrieve it properly.

I also tried this thinking that the response might be asynchronous but it didn’t work:

JavaScript

Advertisement

Answer

The console is empty because the readyState property state 1 merely means that the connection with the server is established.

Furthermore, the XMLHttpRequest object you print to the console is updated immediately when the http-response file is received, which gives the false assumption that it can’t be accessed.

This is more or less a boilerplate code-snippet for waiting for the http-response

JavaScript

Now let’s tailor it with the code you submitted:

JavaScript

This should do it. Notice that event is deprecated and that you would continue using e instead.

Instead of depending on the onreadystatechange property, you could also choose for:

JavaScript

An eventlistener which automatically looks for the succes denoting parameters and is a hack of a lot shorter.

I hope this helps.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement