Tips for integrating NanoHTTPD with AJAX requests

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.

Answer №1

In order for your server response to work properly, it is important to include the following headers:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust Leaflet map size when the containing element is resized (Dash Plotly)

I am encountering some difficulties with dash-leaflet, particularly regarding its width when the parent container is resized. I am utilizing dash-resizable-panels to resize certain divs. Allow me to present a Minimal Reproducible Example (MRE) below: # pi ...

Error: The variable $ has not been declared in the context of the function iterateId

I understand that there are many questions on SO related to this error, but my issue is a bit unique. In my code, I am using a forEach loop to retrieve the IDs and text of elements as shown below: function iterateId(id){ $("input[id*='" + id + ...

Steps for transforming an array of file names into JSON format and including a specific key

I am in the process of creating a new website that will display all the files contained in a specific folder. However, I am facing an issue with converting an array of document names into JSON format. In order to achieve this, I understand that I need to ...

Anticipated a task or procedure but encountered an expression instead

I'm encountering an issue with the following code snippet. JShint is flagging it with "Expected an assignment or function and instead saw an expression". function checkVal(inputField) { ( inputField.val() === '' ) ? inputField.prev( ...

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Error encountered when trying to establish a connection between different domains using PhoneGap or

I am currently utilizing Phonegap/Cordova to establish a connection with the WP-API of Wordpress. The 'Access-Control-Allow-Origin' header is showing up on the requested resource. Here is my ajax setup: jQuery.ajax ({ url: 'linktoserv ...

Generating a new division element with a unique identifier and subsequently making adjustments to it

Just starting out with HTML and JS here, so please excuse my lack of experience and not-so-great English. I have an ID on an HTML element that I want to add content to using a function. Additionally, I need to create another element (inside the first one) ...

Utilize Postman to send a JSON body in a POST request to trigger a stored procedure on Microsoft SQL Server

I need to send a JSON request using the Postman app, utilizing the POST method to retrieve data. My boss, who is overseeing my training, assigned me this task. I've scoured the web for a week but haven't found a solution yet. Initially, I sugges ...

Tips for adjusting the size of a textarea to perfectly fit within a table cell

I have a textarea displayed within an input in a table, but I am looking to resize it so that it completely fills the table cell up to the borders. Here is the logic: <textarea type="textarea" value="{{data.directRowNo}}" id = " ...

Tips for preventing Uncaught SecurityError: Blocking a frame with origin in phonegap

I'm in the process of developing a phonegap application that serves as a miniature browser for a client's website. This app will allow the client's customers to access their favorite pages with ease. Once a user selects a favorite, it will b ...

Dispatching $emit / $broadcast events from multiple areas of the code and capturing them in a single location

I have a practice of sending $emits (or $broadcasts) from various parts of the code and different controllers, but intercepting them all from one centralized place. While this approach seems to be functioning properly, I am unsure if it may be considered b ...

Tips for dividing the AJAX response HTML using jQuery

I have a piece of code that is functioning properly. However, I am having trouble splitting the HTML response using AJAX jQuery. I need to split it into #div1 and #div2 by using "|". Could you please provide a complete code example and explanation, as I am ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

Is it possible to use a hash map to monitor progress while looping through this array in JavaScript?

I've been exploring some algorithmic problems and I'm puzzled about the most efficient way to solve this particular question. While nested for loops are an option, they don't seem like the optimal choice. I'm considering using a hash ma ...

My software consistently triggers the default servlet

I'm encountering an issue with calling a servlet and I could use some assistance. Here is a snippet from my web.xml file: <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.s ...

Is there a way to convert an array into a single comma-separated value using parameters?

Is there a way to parameterize an array as a single name-value pair that is comma separated? I have tried using jQuery $.param, but it creates a parameter for each value in the array instead of just one. Unfortunately, it seems that there is no option or s ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

How can we verify in enzyme that the history.push method was called while utilizing withRouter and connect?

In a stateless React component, I am utilizing withRouter and connect. Within this component, there is a button that triggers a method in props provided by mapDispatchToProps. My goal is to create a test that verifies the button's action of calling h ...

Error in External JavaScript File and Uncaught Reference Error

Wanting to utilize a separate Javascript file with my HTML code, I encountered an issue. Here is the code for the HTML document: <!DOCTYPE html> <html> <a href="javascript:showAlert()">Show Alert!</a> <script type="text/jav ...