Miku_95
Miku_95

Reputation: 21

Save HTTP response as string in JavaScript

How do I save the body of an HTTP request as string and print it? I'm having an HTML file and I'm sending an HTTP request like this:

function loadXMLDoc(str) {
  var url = "http://192.168.178.37?" + str;
  var http = new XMLHttpRequest();

  http.onreadystatechange = function() {
    if (http.readyState === 4) {
      window.alert(http.response);
    }
  }

  http.open('GET', url, true);
  http.send();
}

On the other side the response looks like this:

  char rspText[]  = "value=sensorvalue";
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.printlnf("Content-Length: %d", strlen(rspText));
  client.println();
  client.print(rspText);

My problem is that the http.response which should include to body is always empty. I know that I have probably used the wrong Content-Type. I simply want to send a sensor value back in the response and save it as string for later use.

Upvotes: 2

Views: 2900

Answers (2)

Miku_95
Miku_95

Reputation: 21

The answer was to Disable Local File Restrictions in Safari ...

Upvotes: 0

guest
guest

Reputation: 6708

You tell the browser to expect strlen(rspText) (17) bytes of body, but then by mistake you send the literal string rspText (notice the double quotes) rather than the actual response you had prepared.

Problems like these lead to an HTTP protocol error, and it's probably the case that the browser leaves the .response property empty when this happens.


Also possibly problematic is that HTTP is specified to use CRLF line endings, and it's not clear that your sample server code follows that. Even if browsers are lenient enough to handle LF line endings, there might be some fussy middleware in between that's unsatisfied.

Upvotes: 0

Related Questions