The XMLHttpRequest onload() function is failing to pass an instance of the XMLHttpRequest object

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.

Answer №1

The reason for this behavior is due to the use of an arrow function () =>. In arrow functions, the this keyword is captured lexically and does not change with the context in which it is used. In your scenario, the this is referring to the window context because that is the outermost lexical scope where it was declared.

To resolve this issue, you should convert the arrow function into a regular function so that this points to the xhr object:

xhr.onload = function(){
      console.log("RESPONSE RECEIVED");
      console.log(this); // 'this' should be an XMLHttpRequest object
      console.log(this.status);
      console.log(this.responseText);
};

According to the MDN documentation:

An arrow function does not have its own instance of this. Instead, it uses the value of this from the surrounding lexical scope; arrow functions adhere to standard variable lookup rules. Therefore, if a reference to this cannot be found within the current scope, an arrow function will inherit the value of this from its parent scope.

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

"Implementing middleware controls for email duplicates can prevent poorly designed code structures

I'm looking to implement a node.js express middleware for controlling duplicate emails, and I need a simple and concise code snippet for this. Here is the code from my middleware.js file: // ----------------------------------- MIDDLEWARE FUNCTION ...

How can I retrieve the value from req.body following an AJAX POST request on the server side with Express?

Currently, I am utilizing AJAX to send JSON data: app.use(express.json()); app.use(bodyParser.urlencoded({extended:true})) app.use(express.urlencoded({ extended: true})); const rowObject=JSON.stringify(rowData) $.ajax({ type: "POST&q ...

Error: The property 'branchs' is not defined and cannot be read

models / branch.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const branchSchema = new Schema({ merchant_id: { type: [String], index: true }, contact_name: String, branch: String, phone: String, email: String ...

EJS variable not detected by Visual Studio IDE in JavaScript file

Working on a Node.js project with the express framework and utilizing EJS as the template engine, my IDE of choice is Visual Studio. Encountering an issue when using EJS variables within the same ejs file. Though it renders correctly and functions perfect ...

Ways to retrieve directory information in Next.js hosted on Netlify

Having trouble retrieving a list of directories in Next.js on Netlify. The code works fine on localhost, but once deployed to Netlify, an error is triggered: { "errorType": "Runtime.UnhandledPromiseRejection", "errorMessage": ...

What is the best way to retrieve a png image using a Node.js Express app by sending a request to an API?

I am trying to retrieve a png image from an API endpoint using a nodejs express app. When attempting to fetch and display an image/svg file, everything works as expected. However, when I try the same with a png file, I receive poorly encoded text like thi ...

Creating a functional dropdown form in Ruby On Rails: A Step-by-Step Guide

Having an issue with implementing a dropdown form in the navigation bar of my Rails application. The problem arises randomly - sometimes it works smoothly, while other times I have to refresh the page for it to function properly. The Rails version being u ...

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

Is it achievable for a modal popup to automatically move to a specified location?

I need assistance with... Is it feasible to display an external webpage within a modal window and have that page automatically scroll to a specific section (such as an anchor point)? ...

I am having success posting data through a form, however, the fetch API is not functioning as expected for me

Currently, I am working on a React Project and focusing on creating a signup form. Everything seems to be fine when posting form data using the Form, but things get stuck when I try to use onSubmit={handleSubmit} along with fetch APIs such as axios or just ...

Issues arising from jQuery AJAX request in Chrome extension

BLUF: The AJAX call from my Chrome extension is not functioning properly. AJAX: $.ajax({ type: "GET", url: "http://weather.aero/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=KFBG&hour ...

Unable to group the array based on the key value using Jquery or Javascript

I am looking to group my array values based on specific key values using Jquery/Javascript, but I am facing issues with my current code. Let me explain the code below. var dataArr=[ { "login_id":"9937229853", "alloc ...

Error alert: Blinking display, do not dismiss

I am trying to make it so that when the "enviar" button is clicked, the "resultado" goes from being hidden ("display:none") to being visible ("display:block"). This is my html document: <script type="text/javascript"> function showResu ...

Dealing with extended database operations in node.js

I have a scenario where I need to handle database calls after sending a response to the client. Specifically, I have an endpoint that sends a response to the client, and based on that response, I need to make database calls to create user data. How can I ...

The overlappingmarkerspidifier is throwing an error because it is unable to access the property '__e3_' of an undefined variable

I am attempting to implement the overlapping marker spidifier feature in my code. I followed the instructions provided in this link: functioning code of oms However, upon creating the OverlappingMarkerSpiderfier object, I encounter the error: Uncaught Typ ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Storing JSON data using Vuex

As I am delving into the world of Vuex store used with vue.js, I find myself wanting to implement it in a specific scenario. 1. Is STATE referring to any data, whether static or dynamic, that is provided by the server or stored in a JSON format? TEMPLATE ...

Vue parent component not receiving events properly

Referring to these sources: Forum Post Stack Overflow Question In my project, I am utilizing: CodeSandbox Example The setup involves the parent component listening for events emitted by a child component: mounted() { this.$on("edit-category& ...