Running a jetty server to respond to GET requests has been successful so far. When accessing the request through a browser using localhost:8080/sp or 127.0.0.1:8080/sp, the correct data is returned.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("{foobar: true}");
response.flushBuffer();
out.flush();
out.close();
}
However, troubles arise when trying to access the same URL using JS, as the response body turns out to be empty. This was tested by serving the webpage on both the OS X webserver (port 80) and python SimpleHTTPServer (port 3000), with the same empty response in both cases.
<h1>Single Test Page</h1>
<script>
var httpReq = null;
var url = "http://127.0.0.1:8080/sp";
window.onload = function(){
var myRequest = new XMLHttpRequest();
myRequest.open('get', url);
myRequest.onreadystatechange = function(){
if ((myRequest.readyState == 4) || (myRequest.status == 200)){
alert(myRequest.responseText);
}
}
myRequest.send(null);
}
</script>
This issue could potentially be related to XSS attack prevention. How can the setup be modified to allow JS communication with the servlet? Are there alternative methods for making an HTTP GET request from JS?
Even attempting to add an entry into the /etc/hosts file like so: 127.0.0.1 foo.com and adjusting the JS URL did not resolve the problem.