Using an XMLHttpRequest to obtain a response from a servlet

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.

Answer №1

Yes, the issue lies in the fact that this is a cross-domain request.

There are two possible solutions :

  • utilize JSONP
  • configure CORS headers so that the browser can allow your servlet response to be embedded

Both options are straightforward, but the second one stands out because you only need to set the headers in the servlet code. For instance :

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Request-Method", "GET");

Also, remember to access your html file through http:// rather than file://.

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

Tips for utilizing a function within a callback function using jQuery

When using jQuery's .load() to load HTML files into a parent webpage, I am interested in executing jQuery/JS from the parent page against the loaded HTML file. It seems like this can be achieved with a callback function. The jQuery I'm using is ...

"Encountering a "ReferenceError: document is not defined" error while attempting to run tests on a create-react

Here is the content of my __tests__/App.js file: import React from 'react'; import ReactDOM from 'react-dom'; import App from '../src/containers/App'; it('renders without crashing', () => { const div = documen ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

The issue with `window` not being defined in Nuxt.js when using `apexcharts/vue-ap

I recently came across this example on a website about apex charts and decided to implement it in my project. I made sure to import all the necessary dependencies correctly and didn't reference window anywhere in my code. However, upon adding the file ...

Error: Unable to call topFrame.window.changeSelectedBarStyle because it is not a valid function. What could be causing this

This function is called changeSelectedBarStyle: function changeSelectedBarStyle(tdId){ $("#menuTable td").each(function(index){ if(this.id == tdId){ $(this).removeClass("menuPanel"); $(this).addClass("menuPanelSelected" ...

Hover and Click Card Turning

My card can both hover and click, but there seems to be a small glitch. After clicking on the card and then moving the cursor away from the front, the hover effect doesn't work correctly. It immediately flips back to the front side. The hover effect ...

While trying to install express using Node.js, an error (error:0906D06C :PEM routines : PEM_read_bio npm) occurred

I recently installed node.js on my computer and npm came along with it. However, when I try to execute "npm install express" in my Windows command prompt, I encounter the following error message. Can anyone guide me on how to resolve this issue? C:\U ...

Guidelines for populating data with an array

I have the following array: const dataArr = [[15, 14, 5], [16, 10, 2], [17, 6, 13], [18, 4, 8], [19, 7, 4]]; Now, I am populating another array using the above data as shown below: for (let i=0; i<dataArr.length; i++){ newData.push(dataArr[i]); ...

Execute function when multiple computed properties are true / filled (VueJS)

I am looking to execute a function in my methods section only when all three variables, test1, test2, and test3, are populated. If any of them are empty, I want nothing to happen. I have attempted to achieve this using computed properties and then with a ...

Assign a function in one class to be equivalent to a function in a different class

What is causing this issue and how should it be resolved? class A { constructor() { console.log('constructin A') } public someMethod = (x: string) => { console.log(x) } } class B { private myA: A constructor ...

tips for selecting various API requests based on the selected drop down menu choice

Hey there! I'm looking to enhance my login page by adding a feature that allows users to select from a dropdown menu with different options. Each option will be linked to a specific API, and based on the API response, the user's ability to log in ...

Troubleshooting ASP.NET Ajax and Validator Issues

My web form contains several elements like a TextBox, SaveButton, RequiredFieldValidator, DataGrid, and a paging button all housed within a single UpdatePanel. The SaveButton is responsible for saving the value in the TextBox to the database and updating t ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

"Exploring the Effects of Opacity Gradation in

Is there a way to create a face with an opacity gradient in three.js since rgba is not supported and the alpha is not used? I've heard it might be achievable with a ShaderMaterial and custom attributes, but being new to WebGL, I'm still trying t ...

How to Generate Web Page Output from HTML 5 Canvas without Printer Prompt

Is there a way to achieve silent printing of HTML5 Canvas content? Currently, I am able to print, but a window always pops up prompting me to select a printer and settings. How can I make the browser print to the default printer without any prompts? I am ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Guide on utilizing popup box input to amend CSS (background color)

I'm looking for some guidance on JavaScript and CSS. Is there a way to create a popup box where users can input a color (any main primary color recognized by CSS) and then have the background color of the page change accordingly in an external styles ...

Deactivate the signup button automatically when the user is not present, without the need to refresh

To determine user availability, the system will check the table of users. If the user is available, the signup button will be displayed; otherwise, the button will remain disabled or its color may change. ...

Guide on assigning a material to ColladaLoader or OBJLoader

I've searched extensively through the documentation and numerous examples, but I couldn't find the correct syntax for assigning a material to either a Collada .dae or OBJLoader .obj file. Json files seem to work well when creating a Mesh, with t ...

I am attempting to fetch the posts using an ajax call, however, I am encountering a server error 500 with Wordpress Ajax

After clicking on a pagination link (page number), the post_type, taxonomy, and term_name are retrieved. Using JQuery Variables, these variables are passed to an Ajax WordPress function. Although the Ajax function successfully receives the variables, the W ...