I am facing an issue with a function that sends a basic AJAX request to my server. The JavaScript code in the browser is as follows:
function testRequest() {
var xhr = new XMLHttpRequest();
xhr.onload = () => {
console.log("RESPONSE RECIEVED");
console.log(this); // 'this' should be a XMLHttpRequest object
console.log(this.status);
console.log(this.responseText);
};
xhr.open('POST', `http://server_ip/test`, true);
xhr.send();
}
The server-side code (using Express.js) looks like this:
app.post("/test", (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.status(200).send("testing");
});
Upon calling the function, the response I'm receiving on the browser console is different from what I expected. Here's what it shows:
RESPONSE RECEIVED
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
undefined
Instead of getting the desired output:
RESPONSE RECEIVED
XMLHttpRequest {…}
200
"testing"
This means that the browser seems to receive the server response but for some reason, the 'this' object passed into the onload function appears to be a 'Window' object rather than an 'XMLHttpRequest' object. As a result, the status and responseText variables are not accessible.
Upon inspecting the request in the browser, the response body does contain the expected 'testing' data.