How To Fix “XMLHttpRequest is not defined” Error in JavaScript

XMLHttpRequest is not defined Error in JavaScript

When you stick to old habits and create a network request with XMLHttpRequest in the Node runtime environment, you might see the “XMLHttpRequest is not defined” Error in JavaScript. This article will explain why your script couldn’t run like on your browser and how to fix that issue.

XMLHttpRequest is not defined” Error in JavaScript

Reproduce The Error

Let’s say you have this JavaScript file:

var req = new XMLHttpRequest();
req.open("GET", "https://learnshareit.com/example.json");

This script is designed to create an XMLHttpRequest object on the server and use it to fetch a JSON file, making it ready for data exchange between the server and client.

However, when we run this script with Node.js, an error appears instead:

var req = new XMLHttpRequest();
          ^
ReferenceError: XMLHttpRequest is not defined

The error happens because, by default, Node.js doesn’t come with anything to handle XMLHttpRequest (XHR) objects. While XMLHttpRequest is widely used in AJAX, only browsers (client side) have support for it out of the box.

At the end of the day, W3C defines XMLHttpRequest as an API providing client features for transferring data between it and a server. There is no reason for Node.js to implement and make it a native API.

To solve the problem, you must find third-party solutions that can simulate XMLHttpRequest on the server side. Another choice is to replace it with other libraries with the same functionality.

xmlhttprequest

The node-XMLHttpRequest module is written to emulate the XMLHttpRequest object.

Install it with npm:

npm install xmlhttprequest

Or add it to the package.json file:

{
  "dependencies": {
    "xmlhttprequest": "*"
  }
}

Keep in mind that the current version only supports XMLHttpRequest Level 1. You will need to include the module first before calling the XMLHttpRequest() like usual to create a browser-based XHR object:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var req = new XMLHttpRequest();
req.open("GET", "https://learnshareit.com/example.json");

xhr2

The xhr2 module is newer and also implements the XMLHttpRequest Level 1 specification using native APIs of Node.js.

Install it with npm:

npm install xhr2

Or add it to the package.json file:

{
  "dependencies": {
    "xhr2": "*"
  }
}

Include the module it before calling the XMLHttpRequest() constructor:

var XMLHttpRequest = require('xhr2');
var req = new XMLHttpRequest();
req.open("GET", "https://learnshareit.com/example.json");

It is important to note that xhr2 doesn’t implement some standard features of the W3C XMLHttpRequest specifications, including:

  • cookie processing
  • synchronous operation
  • events for upload progress
  • data: URIs
  • file:// URIs
  • Blog
  • FormData

Fetch API

XMLHttpRequest still exists mainly for historical reasons. The browser still needs to support it for compatibility since many legacy scripts use this object.

When possible, you should replace it with modern APIs like Fetch. Like XMLHttpRequest, it can also send network requests and receive new information when needed. You can use it to get new updates from a server and submit a form without reloading the page.

On the server side, you can install the node-fetch module, an API compatible with client-side  ‘window.fetch’.

Install it with npm:

npm install node-fetch

Or add it to the package.json file:

{
  "dependencies": {
    "node-fetch": "*"
  }
}

And rewrite your code with it:

import fetch from 'node-fetch';
let response = await fetch("https://learnshareit.com/example.json");
if (response.ok) {
    let json = await response.json();
    } else {
    alert("Error: " + response.status);
}

The response object returned by the fetch() function has many promise-based methods, such as:

  • response.json(): allow you to parse the response as a JSON source
  • response.text(): return the response as text

Summary

The “XMLHttpRequest is not defined” Error in JavaScript occurs when you call the XMLHttpRequest() constructor in a Node.js environment. This is a browser-based API, and you will need additional modules or other server-side replacements.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *