or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-xmlhttprequest

XMLHttpRequest for Node.js that emulates the browser XMLHttpRequest object

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/xmlhttprequest@1.8.x

To install, run

npx @tessl/cli install tessl/npm-xmlhttprequest@1.8.0

index.mddocs/

XMLHttpRequest

XMLHttpRequest is a Node.js wrapper for the built-in HTTP client that emulates the browser XMLHttpRequest object. This enables code designed for browsers to run in Node.js environments without modification, improving code reuse and allowing existing browser-based libraries to work seamlessly in server-side environments.

Package Information

  • Package Name: xmlhttprequest
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install xmlhttprequest

Core Imports

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

Note: Use the lowercase string "xmlhttprequest" in your require statement. On case-sensitive systems (e.g., Linux), using uppercase letters won't work.

Basic Usage

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Response:', this.responseText);
  }
};

xhr.open("GET", "http://example.com/api/data");
xhr.send();

Capabilities

XMLHttpRequest Constructor

Creates a new XMLHttpRequest instance that emulates the browser XMLHttpRequest API.

/**
 * XMLHttpRequest constructor
 * Creates a new XMLHttpRequest instance
 */
function XMLHttpRequest();

State Constants

Ready state constants defining the current state of the request.

/**
 * Ready state constants
 */
XMLHttpRequest.prototype.UNSENT = 0;           // Initial state
XMLHttpRequest.prototype.OPENED = 1;          // open() has been called
XMLHttpRequest.prototype.HEADERS_RECEIVED = 2; // Headers have been received
XMLHttpRequest.prototype.LOADING = 3;         // Response body is being received
XMLHttpRequest.prototype.DONE = 4;            // Request completed

Instance Properties

Core properties that track the request state and response data.

/**
 * Current state of the request (0-4)
 */
XMLHttpRequest.prototype.readyState: number;

/**
 * Event handler for ready state changes
 */
XMLHttpRequest.prototype.onreadystatechange: function | null;

/**
 * Response body as text
 */
XMLHttpRequest.prototype.responseText: string;

/**
 * Response body as XML (currently same as responseText)
 */
XMLHttpRequest.prototype.responseXML: string;

/**
 * HTTP status code of the response
 */
XMLHttpRequest.prototype.status: number | null;

/**
 * HTTP status text of the response
 */
XMLHttpRequest.prototype.statusText: string | null;

/**
 * Whether to include credentials in cross-origin requests
 */
XMLHttpRequest.prototype.withCredentials: boolean;

Request Lifecycle Methods

Core methods for managing the HTTP request lifecycle.

/**
 * Opens a connection to the specified URL
 * @param {string} method - HTTP method (GET, POST, PUT, DELETE, HEAD)
 * @param {string} url - URL to connect to
 * @param {boolean} [async=true] - Whether request is asynchronous
 * @param {string} [user] - Username for basic authentication
 * @param {string} [password] - Password for basic authentication
 * @throws {Error} SecurityError if method is not allowed (TRACE, TRACK, CONNECT)
 */
XMLHttpRequest.prototype.open = function(method, url, async, user, password);

/**
 * Sends the request to the server
 * @param {string} [data] - Optional request body data
 * @throws {Error} INVALID_STATE_ERR if not in OPENED state or send already called
 */
XMLHttpRequest.prototype.send = function(data);

/**
 * Aborts the current request
 * Resets the request state and fires abort event
 */
XMLHttpRequest.prototype.abort = function();

Header Management Methods

Methods for setting request headers and retrieving response headers.

/**
 * Sets a request header
 * @param {string} header - Header name
 * @param {string} value - Header value
 * @throws {Error} INVALID_STATE_ERR if not in OPENED state or send flag is true
 */
XMLHttpRequest.prototype.setRequestHeader = function(header, value);

/**
 * Gets a response header value
 * @param {string} header - Header name to retrieve
 * @returns {string|null} Header value or null if not found/not available
 */
XMLHttpRequest.prototype.getResponseHeader = function(header);

/**
 * Gets all response headers as a string
 * @returns {string} All response headers separated by CRLF, excluding cookies
 */
XMLHttpRequest.prototype.getAllResponseHeaders = function();

/**
 * Gets a request header value
 * @param {string} name - Header name to retrieve
 * @returns {string} Header value or empty string if not set
 */
XMLHttpRequest.prototype.getRequestHeader = function(name);

Event Handling Methods

Methods for managing event listeners and dispatching events.

/**
 * Adds an event listener
 * @param {string} event - Event name (readystatechange, load, error, abort, loadstart, loadend)
 * @param {function} callback - Function to call when event occurs
 */
XMLHttpRequest.prototype.addEventListener = function(event, callback);

/**
 * Removes an event listener
 * @param {string} event - Event name
 * @param {function} callback - Function to remove (must be same reference)
 */
XMLHttpRequest.prototype.removeEventListener = function(event, callback);

/**
 * Dispatches an event to all registered listeners
 * @param {string} event - Event name to dispatch
 */
XMLHttpRequest.prototype.dispatchEvent = function(event);

Non-Standard Methods

Additional methods that extend beyond the W3C XMLHttpRequest specification.

/**
 * Disables or enables header validation
 * This is not part of the W3C XMLHttpRequest specification
 * @param {boolean} state - Enable (true) or disable (false) header checking
 */
XMLHttpRequest.prototype.setDisableHeaderCheck = function(state);

/**
 * Handles errors by setting appropriate status and response values
 * Internal error handler exposed as a public method
 * @param {Error} error - Error object to handle
 */
XMLHttpRequest.prototype.handleError = function(error);

Supported Features

  • Request Methods: GET, POST, PUT, DELETE, HEAD
  • Protocols: HTTP, HTTPS, file:// (for local files)
  • Request Types: Both asynchronous and synchronous requests
  • Authentication: Basic authentication support
  • Redirects: Automatic handling of 301, 302, 303, 307 redirects
  • Headers: Full request and response header management
  • Events: Complete event system matching browser XMLHttpRequest
  • Cross-Origin: No same-origin policy enforcement (all domains accessible)

Events

The XMLHttpRequest instance fires several events during the request lifecycle:

  • readystatechange: Fired when readyState changes
  • loadstart: Fired when the request starts
  • load: Fired when the request completes successfully
  • loadend: Fired when the request ends (success or failure)
  • error: Fired when an error occurs
  • abort: Fired when the request is aborted

Error Handling

The implementation handles various error conditions:

  • SecurityError: Thrown for forbidden request methods (TRACE, TRACK, CONNECT)
  • INVALID_STATE_ERR: Thrown when methods are called at inappropriate times
  • Network Errors: Sets status to 0 and populates responseText with error details
  • File System Errors: For file:// protocol requests that fail to read local files

Usage Examples

Basic GET Request

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (this.readyState === 4) {
    if (this.status === 200) {
      console.log('Success:', this.responseText);
    } else {
      console.log('Error:', this.status, this.statusText);
    }
  }
};

xhr.open("GET", "https://api.example.com/data");
xhr.send();

POST Request with Data

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

xhr.open("POST", "https://api.example.com/users");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function() {
  if (this.readyState === 4) {
    console.log('Response:', this.responseText);
  }
};

var userData = JSON.stringify({
  name: "John Doe",
  email: "john@example.com"
});

xhr.send(userData);

Using Event Listeners

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

xhr.addEventListener('loadstart', function() {
  console.log('Request started');
});

xhr.addEventListener('load', function() {
  console.log('Request completed successfully');
});

xhr.addEventListener('error', function() {
  console.log('Request failed');
});

xhr.open("GET", "https://api.example.com/data");
xhr.send();

Synchronous Request

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

// Third parameter false makes it synchronous
xhr.open("GET", "https://api.example.com/data", false);
xhr.send();

// Response is immediately available
console.log('Status:', xhr.status);
console.log('Response:', xhr.responseText);

File System Access

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (this.readyState === 4) {
    if (this.status === 200) {
      console.log('File contents:', this.responseText);
    } else {
      console.log('File read error');
    }
  }
};

xhr.open("GET", "file:///path/to/local/file.txt");
xhr.send();