I am currently working on setting up NanoHTTPD on an android device to respond to AJAX requests in a way that the requesting javascript can understand the response.
Here is my implementation of the NanoHTTPD serve method:
public NanoHTTPD.Response serve(String uri, NanoHTTPD.Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
String msg = "Hello, you have connected.";
return newFixedLengthResponse( msg );
}
When connecting from the local web browser to "", I get a page with source code like this:
<html>
<head></head>
<body>Hello, you have connected.</body>
</html>
Everything seems fine so far, but I'm puzzled about where the HTML formatting comes into play.
The issue arises when I try to pass data using AJAX from JavaScript:
$.ajax({
url: 'http://127.0.0.1:8080',
type: 'POST',
data:{ printData: dataToPrint },
success: function(d){
alert('success');
},
error: function (jqXHR, textStatus) {
alert("failed, jqXHR: " + jqXHR.responseText + " " + jQuery.parseJSON(jqXHR.responseText) + " textStatus: " + textStatus);
}
})
No matter what methods or configurations I try, the server always fails to send back the expected response and triggers the error/fail method instead. The return message never contains any data - neither the status nor the return message itself.
I've experimented with different return values from the Serve method, such as:
String mime_type = NanoHTTPD.MIME_PLAINTEXT;
String msg = "{\"status\":\"1\",\"responseText\":\"this is the response\"}";
InputStream testReply = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
// return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "", msg);
// return new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, mime_type, testReply);
// return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.OK, mime_type, msg);
// return NanoHTTPD.newFixedLengthResponse(msg);
None of these attempts have been successful.
I also tested this JavaScript snippet:
$.get("http://127.0.0.1:8080", function( my_var ) {
console.log(my_var);
});
Although the breakpoint on NanoHTTPD was triggered, the JavaScript method did not execute at all.