Search code examples
javascriptajaxnanohttpd

How to have NanoHTTPD respond to AJAX


I'm attempting to get NanoHTTPD (on an android device) to respond to AJAX requests in a way that the requesting javascript can interpret the response.

I've implemented 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 );
    }

And if I connect from the local webbrowser to "http://127.0.0.1:8080" it loads a page with the source:

<html>
    <head></head>
    <body>Hello, you have connected.</body>
</html>

So far so good, although I'm not sure where the html formatting is introduced.

But what I am stuck on is if I use AJAX from javascript to try to pass data:

$.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);
        }
    })

(This is just one example, I've tried success/fail/done/error methods, I've tried specifying the datatype, I've tried different parameters in the return functions, none of it works). When this javascript is run the NanoHTTPD server receives the printData just fine, but when it sends it response it is only ever the error/fail method that is triggered and the method parameters never contain anything - I cannot set the status or the return message or anything.

I've tried different returns from the Serve method including:

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 work.

I also tried this javascript:

$.get("http://127.0.0.1:8080", function( my_var ) {
        console.log(my_var);
    });

If this is run my breakpoint on NanoHTTPD is triggered, but the javascript method is not triggered at all.


Solution

  • I think you need to add these headers in your server response:

        Access-Control-Allow-Origin: *
        Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
        Access-Control-Max-Age: 86400