A wrapper for asynchronous HTTP requests supporting XMLHttpRequest, JSONP, CORS, and CommonJS Promises
npx @tessl/cli install tessl/npm-reqwest@2.0.00
# Reqwest
1
2
Reqwest is a comprehensive AJAX library providing XMLHttpRequest, JSONP, CORS, and CommonJS Promises support. It offers a flexible API for making asynchronous HTTP requests with extensive configuration options, cross-browser compatibility (IE6+), and a promise-like interface for modern JavaScript development.
3
4
## Package Information
5
6
- **Package Name**: reqwest
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install reqwest`
10
11
## Core Imports
12
13
```javascript
14
import reqwest from "reqwest";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const reqwest = require("reqwest");
21
```
22
23
For browser environments:
24
25
```html
26
<script src="reqwest.js"></script>
27
<!-- reqwest is available as global variable -->
28
```
29
30
## Basic Usage
31
32
```javascript
33
// Simple GET request
34
reqwest('path/to/data.json', function(resp) {
35
console.log(resp);
36
});
37
38
// POST request with data
39
reqwest({
40
url: 'path/to/api',
41
method: 'post',
42
data: { name: 'John', age: 30 },
43
success: function(resp) {
44
console.log('Success:', resp);
45
},
46
error: function(err) {
47
console.log('Error:', err);
48
}
49
});
50
51
// Using promises
52
reqwest({
53
url: 'path/to/data.json',
54
type: 'json'
55
})
56
.then(function(resp) {
57
console.log('Data:', resp);
58
})
59
.catch(function(err) {
60
console.log('Error:', err);
61
});
62
```
63
64
## Node.js Usage
65
66
Reqwest can be used in Node.js environments through the `xhr2` peer dependency:
67
68
```bash
69
npm install reqwest xhr2
70
```
71
72
```javascript
73
const reqwest = require('reqwest');
74
75
// Works the same as in browser environments
76
reqwest({
77
url: 'https://api.example.com/data',
78
type: 'json'
79
})
80
.then(function(data) {
81
console.log('Data:', data);
82
})
83
.catch(function(err) {
84
console.error('Error:', err);
85
});
86
```
87
88
**Note**: For comprehensive Node.js HTTP client functionality, consider using specialized libraries like `mikeal/request` as reqwest is primarily designed for browser environments.
89
90
## Architecture
91
92
Reqwest provides a comprehensive AJAX solution built around several key concepts:
93
94
- **Universal API**: Single function interface that handles multiple request patterns (URL string, options object)
95
- **Cross-browser Support**: Automatic XHR selection (XMLHttpRequest, XDomainRequest, ActiveXObject) based on browser capabilities
96
- **Promise-like Interface**: Chainable methods (`then`, `fail`, `always`, `catch`) for modern async patterns
97
- **Multiple Response Types**: Automatic or manual content type handling (JSON, JSONP, XML, HTML, Text)
98
- **Utility Functions**: Form serialization and query string utilities for data processing
99
- **Framework Integration**: Built-in Ender support and jQuery compatibility layer
100
101
## Capabilities
102
103
### Core Request Functionality
104
105
Primary AJAX request functionality supporting all HTTP methods, multiple data formats, and comprehensive configuration options.
106
107
```javascript { .api }
108
/**
109
* Creates and executes an AJAX request
110
* @param {string|Object} options - URL string or configuration object
111
* @param {Function} callback - Optional success callback
112
* @returns {Object} Request object with promise-like interface
113
*/
114
function reqwest(options, callback);
115
116
interface RequestOptions {
117
url: string;
118
method?: string; // Default: 'GET'
119
type?: string; // 'json' | 'xml' | 'html' | 'text' | 'js' | 'jsonp'
120
data?: any; // Request data (object, string, FormData)
121
headers?: Object; // Custom headers
122
contentType?: string; // Request content type
123
timeout?: number; // Request timeout in milliseconds
124
async?: boolean; // Asynchronous flag (default: true)
125
processData?: boolean; // Whether to process data (default: true)
126
crossOrigin?: boolean; // Enable cross-origin requests
127
withCredentials?: boolean; // Include credentials in cross-origin requests
128
success?: Function; // Success callback
129
error?: Function; // Error callback
130
complete?: Function; // Always-called completion callback
131
before?: Function; // Pre-request callback with XHR object
132
jsonpCallback?: string; // JSONP callback parameter name
133
jsonpCallbackName?: string; // Specific JSONP callback function name
134
xhr?: Function; // Custom XHR factory function
135
dataFilter?: Function; // Response filtering function
136
}
137
```
138
139
[Core Requests](./core-requests.md)
140
141
### Promise-like Interface
142
143
Chainable methods for handling request success, failure, and completion with modern async patterns.
144
145
```javascript { .api }
146
interface RequestPromise {
147
then(success?: Function, fail?: Function): RequestPromise;
148
fail(fn: Function): RequestPromise;
149
always(fn: Function): RequestPromise;
150
catch(fn: Function): RequestPromise;
151
abort(): RequestPromise;
152
retry(): RequestPromise;
153
}
154
```
155
156
[Promise Interface](./promise-interface.md)
157
158
### Form Serialization Utilities
159
160
Comprehensive form handling utilities for converting form elements to various data formats (query strings, objects, arrays).
161
162
```javascript { .api }
163
/**
164
* Serializes form elements to various formats
165
* @param {Element|NodeList} elements - Form elements to serialize
166
* @param {Object} options - Serialization options
167
* @returns {string|Object|Array} Serialized data
168
*/
169
reqwest.serialize(elements, options);
170
171
/**
172
* Serializes form elements to array of name/value pairs
173
* @param {Element|NodeList} elements - Form elements
174
* @returns {Array} Array of {name, value} objects
175
*/
176
reqwest.serializeArray(elements);
177
178
/**
179
* Converts object to URL query string
180
* @param {Object} object - Data to serialize
181
* @param {boolean} traditional - Use traditional array serialization
182
* @returns {string} Query string
183
*/
184
reqwest.toQueryString(object, traditional);
185
186
/**
187
* Gets the JSONP callback prefix used for generating callback names
188
* @returns {string} Callback prefix string
189
*/
190
reqwest.getcallbackPrefix();
191
```
192
193
[Utilities](./utilities.md)
194
195
### Configuration and Compatibility
196
197
Global configuration options and jQuery/Zepto compatibility layer for seamless migration from other AJAX libraries.
198
199
```javascript { .api }
200
/**
201
* Sets global default options for all requests
202
* @param {Object} options - Global configuration options
203
*/
204
reqwest.ajaxSetup(options);
205
206
/**
207
* jQuery/Zepto compatibility layer
208
* @param {Object} options - jQuery-style options
209
* @param {Function} callback - Optional success callback
210
* @returns {Object} Request object
211
*/
212
reqwest.compat(options, callback);
213
```
214
215
[jQuery Compatibility](./jquery-compat.md)
216
217
## Types
218
219
```javascript { .api }
220
/**
221
* Callback function for successful requests
222
* @param {any} response - Parsed response data (JSON, XML, HTML, text, etc.)
223
*/
224
type SuccessCallback = (response: any) => void;
225
226
/**
227
* Callback function for failed requests
228
* @param {XMLHttpRequest} xhr - XMLHttpRequest object that failed
229
* @param {string} message - Error message ('Request is aborted: timeout', etc.)
230
* @param {any} error - Additional error context (parsing errors, etc.)
231
*/
232
type ErrorCallback = (xhr: XMLHttpRequest, message: string, error: any) => void;
233
234
/**
235
* Callback function always called on completion
236
* @param {any} response - Response data (same as success) or XMLHttpRequest object (on error)
237
*/
238
type CompleteCallback = (response: any) => void;
239
240
/**
241
* Pre-request callback function
242
* @param {XMLHttpRequest} xhr - XMLHttpRequest object before sending
243
*/
244
type BeforeCallback = (xhr: XMLHttpRequest) => void;
245
246
/**
247
* Response filtering function
248
* @param {any} data - Raw response data
249
* @param {string} type - Response type
250
* @returns {any} Filtered response data
251
*/
252
type DataFilter = (data: any, type: string) => any;
253
```