XMLHttpRequest for Node.js that emulates the browser XMLHttpRequest object
npx @tessl/cli install tessl/npm-xmlhttprequest@1.8.0XMLHttpRequest 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.
npm install xmlhttprequestvar 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.
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();Creates a new XMLHttpRequest instance that emulates the browser XMLHttpRequest API.
/**
* XMLHttpRequest constructor
* Creates a new XMLHttpRequest instance
*/
function XMLHttpRequest();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 completedCore 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;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();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);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);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);The XMLHttpRequest instance fires several events during the request lifecycle:
readyState changesThe implementation handles various error conditions:
status to 0 and populates responseText with error detailsvar 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();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);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();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);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();