0
# XMLHttpRequest
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: xmlhttprequest
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install xmlhttprequest`
10
11
## Core Imports
12
13
```javascript
14
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
15
```
16
17
Note: Use the lowercase string "xmlhttprequest" in your require statement. On case-sensitive systems (e.g., Linux), using uppercase letters won't work.
18
19
## Basic Usage
20
21
```javascript
22
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
23
var xhr = new XMLHttpRequest();
24
25
xhr.onreadystatechange = function() {
26
if (this.readyState === 4) {
27
console.log('Status:', this.status);
28
console.log('Response:', this.responseText);
29
}
30
};
31
32
xhr.open("GET", "http://example.com/api/data");
33
xhr.send();
34
```
35
36
## Capabilities
37
38
### XMLHttpRequest Constructor
39
40
Creates a new XMLHttpRequest instance that emulates the browser XMLHttpRequest API.
41
42
```javascript { .api }
43
/**
44
* XMLHttpRequest constructor
45
* Creates a new XMLHttpRequest instance
46
*/
47
function XMLHttpRequest();
48
```
49
50
### State Constants
51
52
Ready state constants defining the current state of the request.
53
54
```javascript { .api }
55
/**
56
* Ready state constants
57
*/
58
XMLHttpRequest.prototype.UNSENT = 0; // Initial state
59
XMLHttpRequest.prototype.OPENED = 1; // open() has been called
60
XMLHttpRequest.prototype.HEADERS_RECEIVED = 2; // Headers have been received
61
XMLHttpRequest.prototype.LOADING = 3; // Response body is being received
62
XMLHttpRequest.prototype.DONE = 4; // Request completed
63
```
64
65
### Instance Properties
66
67
Core properties that track the request state and response data.
68
69
```javascript { .api }
70
/**
71
* Current state of the request (0-4)
72
*/
73
XMLHttpRequest.prototype.readyState: number;
74
75
/**
76
* Event handler for ready state changes
77
*/
78
XMLHttpRequest.prototype.onreadystatechange: function | null;
79
80
/**
81
* Response body as text
82
*/
83
XMLHttpRequest.prototype.responseText: string;
84
85
/**
86
* Response body as XML (currently same as responseText)
87
*/
88
XMLHttpRequest.prototype.responseXML: string;
89
90
/**
91
* HTTP status code of the response
92
*/
93
XMLHttpRequest.prototype.status: number | null;
94
95
/**
96
* HTTP status text of the response
97
*/
98
XMLHttpRequest.prototype.statusText: string | null;
99
100
/**
101
* Whether to include credentials in cross-origin requests
102
*/
103
XMLHttpRequest.prototype.withCredentials: boolean;
104
```
105
106
### Request Lifecycle Methods
107
108
Core methods for managing the HTTP request lifecycle.
109
110
```javascript { .api }
111
/**
112
* Opens a connection to the specified URL
113
* @param {string} method - HTTP method (GET, POST, PUT, DELETE, HEAD)
114
* @param {string} url - URL to connect to
115
* @param {boolean} [async=true] - Whether request is asynchronous
116
* @param {string} [user] - Username for basic authentication
117
* @param {string} [password] - Password for basic authentication
118
* @throws {Error} SecurityError if method is not allowed (TRACE, TRACK, CONNECT)
119
*/
120
XMLHttpRequest.prototype.open = function(method, url, async, user, password);
121
122
/**
123
* Sends the request to the server
124
* @param {string} [data] - Optional request body data
125
* @throws {Error} INVALID_STATE_ERR if not in OPENED state or send already called
126
*/
127
XMLHttpRequest.prototype.send = function(data);
128
129
/**
130
* Aborts the current request
131
* Resets the request state and fires abort event
132
*/
133
XMLHttpRequest.prototype.abort = function();
134
```
135
136
### Header Management Methods
137
138
Methods for setting request headers and retrieving response headers.
139
140
```javascript { .api }
141
/**
142
* Sets a request header
143
* @param {string} header - Header name
144
* @param {string} value - Header value
145
* @throws {Error} INVALID_STATE_ERR if not in OPENED state or send flag is true
146
*/
147
XMLHttpRequest.prototype.setRequestHeader = function(header, value);
148
149
/**
150
* Gets a response header value
151
* @param {string} header - Header name to retrieve
152
* @returns {string|null} Header value or null if not found/not available
153
*/
154
XMLHttpRequest.prototype.getResponseHeader = function(header);
155
156
/**
157
* Gets all response headers as a string
158
* @returns {string} All response headers separated by CRLF, excluding cookies
159
*/
160
XMLHttpRequest.prototype.getAllResponseHeaders = function();
161
162
/**
163
* Gets a request header value
164
* @param {string} name - Header name to retrieve
165
* @returns {string} Header value or empty string if not set
166
*/
167
XMLHttpRequest.prototype.getRequestHeader = function(name);
168
```
169
170
### Event Handling Methods
171
172
Methods for managing event listeners and dispatching events.
173
174
```javascript { .api }
175
/**
176
* Adds an event listener
177
* @param {string} event - Event name (readystatechange, load, error, abort, loadstart, loadend)
178
* @param {function} callback - Function to call when event occurs
179
*/
180
XMLHttpRequest.prototype.addEventListener = function(event, callback);
181
182
/**
183
* Removes an event listener
184
* @param {string} event - Event name
185
* @param {function} callback - Function to remove (must be same reference)
186
*/
187
XMLHttpRequest.prototype.removeEventListener = function(event, callback);
188
189
/**
190
* Dispatches an event to all registered listeners
191
* @param {string} event - Event name to dispatch
192
*/
193
XMLHttpRequest.prototype.dispatchEvent = function(event);
194
```
195
196
### Non-Standard Methods
197
198
Additional methods that extend beyond the W3C XMLHttpRequest specification.
199
200
```javascript { .api }
201
/**
202
* Disables or enables header validation
203
* This is not part of the W3C XMLHttpRequest specification
204
* @param {boolean} state - Enable (true) or disable (false) header checking
205
*/
206
XMLHttpRequest.prototype.setDisableHeaderCheck = function(state);
207
208
/**
209
* Handles errors by setting appropriate status and response values
210
* Internal error handler exposed as a public method
211
* @param {Error} error - Error object to handle
212
*/
213
XMLHttpRequest.prototype.handleError = function(error);
214
```
215
216
## Supported Features
217
218
- **Request Methods**: GET, POST, PUT, DELETE, HEAD
219
- **Protocols**: HTTP, HTTPS, file:// (for local files)
220
- **Request Types**: Both asynchronous and synchronous requests
221
- **Authentication**: Basic authentication support
222
- **Redirects**: Automatic handling of 301, 302, 303, 307 redirects
223
- **Headers**: Full request and response header management
224
- **Events**: Complete event system matching browser XMLHttpRequest
225
- **Cross-Origin**: No same-origin policy enforcement (all domains accessible)
226
227
## Events
228
229
The XMLHttpRequest instance fires several events during the request lifecycle:
230
231
- **readystatechange**: Fired when `readyState` changes
232
- **loadstart**: Fired when the request starts
233
- **load**: Fired when the request completes successfully
234
- **loadend**: Fired when the request ends (success or failure)
235
- **error**: Fired when an error occurs
236
- **abort**: Fired when the request is aborted
237
238
## Error Handling
239
240
The implementation handles various error conditions:
241
242
- **SecurityError**: Thrown for forbidden request methods (TRACE, TRACK, CONNECT)
243
- **INVALID_STATE_ERR**: Thrown when methods are called at inappropriate times
244
- **Network Errors**: Sets `status` to 0 and populates `responseText` with error details
245
- **File System Errors**: For file:// protocol requests that fail to read local files
246
247
## Usage Examples
248
249
### Basic GET Request
250
251
```javascript
252
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
253
var xhr = new XMLHttpRequest();
254
255
xhr.onreadystatechange = function() {
256
if (this.readyState === 4) {
257
if (this.status === 200) {
258
console.log('Success:', this.responseText);
259
} else {
260
console.log('Error:', this.status, this.statusText);
261
}
262
}
263
};
264
265
xhr.open("GET", "https://api.example.com/data");
266
xhr.send();
267
```
268
269
### POST Request with Data
270
271
```javascript
272
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
273
var xhr = new XMLHttpRequest();
274
275
xhr.open("POST", "https://api.example.com/users");
276
xhr.setRequestHeader("Content-Type", "application/json");
277
278
xhr.onreadystatechange = function() {
279
if (this.readyState === 4) {
280
console.log('Response:', this.responseText);
281
}
282
};
283
284
var userData = JSON.stringify({
285
name: "John Doe",
286
email: "john@example.com"
287
});
288
289
xhr.send(userData);
290
```
291
292
### Using Event Listeners
293
294
```javascript
295
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
296
var xhr = new XMLHttpRequest();
297
298
xhr.addEventListener('loadstart', function() {
299
console.log('Request started');
300
});
301
302
xhr.addEventListener('load', function() {
303
console.log('Request completed successfully');
304
});
305
306
xhr.addEventListener('error', function() {
307
console.log('Request failed');
308
});
309
310
xhr.open("GET", "https://api.example.com/data");
311
xhr.send();
312
```
313
314
### Synchronous Request
315
316
```javascript
317
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
318
var xhr = new XMLHttpRequest();
319
320
// Third parameter false makes it synchronous
321
xhr.open("GET", "https://api.example.com/data", false);
322
xhr.send();
323
324
// Response is immediately available
325
console.log('Status:', xhr.status);
326
console.log('Response:', xhr.responseText);
327
```
328
329
### File System Access
330
331
```javascript
332
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
333
var xhr = new XMLHttpRequest();
334
335
xhr.onreadystatechange = function() {
336
if (this.readyState === 4) {
337
if (this.status === 200) {
338
console.log('File contents:', this.responseText);
339
} else {
340
console.log('File read error');
341
}
342
}
343
};
344
345
xhr.open("GET", "file:///path/to/local/file.txt");
346
xhr.send();
347
```