0

I am trying to send an HTTP request from JS using XMLHttpRequest and receive it in Java server using socket.

I am able to send the request, but the issue with the response is that I am not getting it.

document.getElementById("Update").addEventListener("click", function() {
  var xhttp;
  var url = "http://192.168.43.1:8081/update";
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
        alert(this.responseText);
        alert(this.status);
    }
};

The status it returns is zero.

Here is my Java code:

try {
  String response = "";
  response = in.readLine();
  System.out.println(response);

  requestParser = response.split(" ");
  requestType = requestParser[0];
  pathFromClient = requestParser[1];
  http = requestParser[2];

  out.write("HTTP/1.1 200 OK");
  out.flush();
  socket.shutdownOutput();
  socket.close();
} catch (Exception e) {
  e.printStackTrace();
}
ocrdu
  • 2,172
  • 6
  • 15
  • 22
Dev Ques
  • 9
  • 1
  • an XHR needs to be `open()`ed and then you need to `send()` before a request is actually made - you've created a var called `url` ... but that doesn't magically get opened because you've created an XHR just after it - may I suggest a brief read of some [documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) – Bravo Dec 04 '20 at 06:17
  • What you are sending is not a valid HTTP response. Please don't second-guess how HTTP works but instead follow the actual standard - there is a reason standards exist. – Steffen Ullrich Dec 04 '20 at 06:19
  • 1
    Once you get your request and response sorted out, you'll probably also need to understand [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) as well – Bravo Dec 04 '20 at 06:20

1 Answers1

0

You forgot some bits. I may have forgotten some bits as well; I didn't test this, just typed it in, but you get the idea.

var url = "http://192.168.43.1:8081/update";
let xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    alert(this.responseText);
  }
}
xhttp.send(null);
ocrdu
  • 2,172
  • 6
  • 15
  • 22