0

Im calling a Java App that is called like "http://localhost:32567?test=aaa" trying to send a a text response to a browser that connects. Response I send is like

HTTP/1.1 200 OK
Content-Type: text/xml
Cache-Control: no-cache
Date: Thu Nov 02 15:56:26 NZDT 2017

<?xml version="1.0" ?><root><message>hello world</message><status>OK</status></root>

When I open the page in browser it works fine and but when I call it using AJAX as Post request the HTTP status returned is 0?

this is code im running in the browser

   var http_request = new XMLHttpRequest();
   http_request.overrideMimeType('text/xml');
   http_request.onreadystatechange = function() {
      alert(http_request.readyState + " " + http_request.status);
   };
   http_request.open('POST', "http://localhost:32567?test=aaa", true);
   http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   http_request.send("");

response i get is

1 0
2 0
4 0

where I expect to get

4 200

The Java Test Code sending the response is as follows

import java.io.*;
import java.net.*;

public class test {
    public test() throws Exception {
        ServerSocket ss = new ServerSocket(32567);

        Socket client = null;
        while ((client = ss.accept()) != null) {
           boolean sentOut = false;
           BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
           String output = "HTTP/1.1 200 OK\nContent-Type: text/xml\nCache-Control: no-cache\nDate: " + (new java.util.Date()) + "\n\n<?xml version=\"1.0\" ?><root><message>test</message><status>OK</status></root>\n";
           System.out.println("--------------------------\n" +  output);
           out.write(output);
           out.flush();
           out.close();
           client.close();
        }
    }

    public static void main(String args[]) throws Exception {
        new test();
    }
}
zackhalil
  • 455
  • 3
  • 14
  • @DannyFardyJhonstonBermúdez i updated the above to show code used – zackhalil Nov 02 '17 at 03:28
  • 1
    Unless your JS page is also running from `localhost:32567`, you'll be running into a CORS issue. Check your browser's console for an error that looks like *"No Access-Control-Allow-Origin header present..."* – Phil Nov 02 '17 at 04:05
  • Possible duplicate of [Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) – Phil Nov 02 '17 at 04:05

1 Answers1

-1

As Phil suggested the issue is with CORS. Add a header Access-Control-Allow-Origin: * to the response and the browser is compromised.

James Jithin
  • 10,183
  • 5
  • 36
  • 51