0
# Request Building
1
2
Comprehensive request configuration with headers, query parameters, body data, and request options for building HTTP requests with the fluent chainable interface.
3
4
## Capabilities
5
6
### Header Management
7
8
Methods for setting, getting, and removing HTTP headers.
9
10
```javascript { .api }
11
/**
12
* Set request header field to value
13
* @param {string|object} field - Header field name or object of field/value pairs
14
* @param {string} [value] - Header field value (when field is string)
15
* @returns {Request} Request instance for chaining
16
*/
17
Request.prototype.set(field, value?): Request;
18
19
/**
20
* Get request header field value
21
* @param {string} field - Header field name
22
* @returns {string} Header field value
23
*/
24
Request.prototype.get(field): string;
25
26
/**
27
* Alias for get() - Get request header field value
28
* @param {string} field - Header field name
29
* @returns {string} Header field value
30
*/
31
Request.prototype.getHeader(field): string;
32
33
/**
34
* Remove request header field
35
* @param {string} field - Header field name to remove
36
* @returns {Request} Request instance for chaining
37
*/
38
Request.prototype.unset(field): Request;
39
```
40
41
**Usage Examples:**
42
43
```javascript
44
const superagent = require('superagent');
45
46
// Set single header
47
superagent
48
.post('https://api.example.com/users')
49
.set('Authorization', 'Bearer token123')
50
.set('User-Agent', 'MyApp/1.0');
51
52
// Set multiple headers with object
53
superagent
54
.post('https://api.example.com/users')
55
.set({
56
'Authorization': 'Bearer token123',
57
'Content-Type': 'application/json',
58
'Accept': 'application/json'
59
});
60
61
// Get header value
62
const request = superagent.post('https://api.example.com/users');
63
request.set('Authorization', 'Bearer token123');
64
console.log(request.get('Authorization')); // 'Bearer token123'
65
66
// Remove header
67
request.unset('Authorization');
68
```
69
70
### Content Type Management
71
72
Convenient methods for setting Content-Type and Accept headers.
73
74
```javascript { .api }
75
/**
76
* Set Content-Type header using MIME type or shorthand
77
* @param {string} type - MIME type or shorthand (json, form, xml)
78
* @returns {Request} Request instance for chaining
79
*/
80
Request.prototype.type(type): Request;
81
82
/**
83
* Set Accept header using MIME type or shorthand
84
* @param {string} type - MIME type or shorthand (json, form, xml)
85
* @returns {Request} Request instance for chaining
86
*/
87
Request.prototype.accept(type): Request;
88
```
89
90
**Usage Examples:**
91
92
```javascript
93
// Using MIME types
94
superagent
95
.post('https://api.example.com/users')
96
.type('application/json')
97
.accept('application/json');
98
99
// Using shorthands
100
superagent
101
.post('https://api.example.com/users')
102
.type('json') // Sets Content-Type: application/json
103
.accept('json'); // Sets Accept: application/json
104
105
// Common shorthands
106
superagent.post('/form').type('form'); // application/x-www-form-urlencoded
107
superagent.post('/xml').type('xml'); // application/xml
108
superagent.get('/data').accept('text'); // text/plain
109
```
110
111
### Query Parameters
112
113
Methods for adding query string parameters to requests.
114
115
```javascript { .api }
116
/**
117
* Add query parameters to request URL
118
* @param {string|object} value - Query string or object of key/value pairs
119
* @returns {Request} Request instance for chaining
120
*/
121
Request.prototype.query(value): Request;
122
```
123
124
**Usage Examples:**
125
126
```javascript
127
// Query with object
128
superagent
129
.get('https://api.example.com/users')
130
.query({ page: 1, limit: 10, sort: 'name' });
131
// Results in: https://api.example.com/users?page=1&limit=10&sort=name
132
133
// Query with string
134
superagent
135
.get('https://api.example.com/users')
136
.query('page=1&limit=10');
137
138
// Multiple query calls (cumulative)
139
superagent
140
.get('https://api.example.com/users')
141
.query({ page: 1 })
142
.query({ limit: 10 })
143
.query('sort=name');
144
145
// Array values
146
superagent
147
.get('https://api.example.com/users')
148
.query({ tags: ['javascript', 'node'] });
149
// Results in: https://api.example.com/users?tags=javascript&tags=node
150
```
151
152
### Request Body Data
153
154
Methods for sending data in the request body.
155
156
```javascript { .api }
157
/**
158
* Send data as request body
159
* @param {any} data - Data to send (object, string, Buffer, etc.)
160
* @returns {Request} Request instance for chaining
161
*/
162
Request.prototype.send(data): Request;
163
```
164
165
**Usage Examples:**
166
167
```javascript
168
// JSON data (automatically sets Content-Type)
169
superagent
170
.post('https://api.example.com/users')
171
.send({ name: 'John', email: 'john@example.com' });
172
173
// Form data
174
superagent
175
.post('https://api.example.com/login')
176
.type('form')
177
.send({ username: 'user', password: 'pass' });
178
179
// String data
180
superagent
181
.post('https://api.example.com/data')
182
.type('text')
183
.send('Hello World');
184
185
// Buffer data
186
const buffer = Buffer.from('binary data');
187
superagent
188
.post('https://api.example.com/upload')
189
.type('application/octet stream')
190
.send(buffer);
191
192
// Multiple send calls (merged for objects)
193
superagent
194
.post('https://api.example.com/users')
195
.send({ name: 'John' })
196
.send({ email: 'john@example.com' });
197
// Results in: { name: 'John', email: 'john@example.com' }
198
```
199
200
### Response Configuration
201
202
Methods for configuring response handling and parsing.
203
204
```javascript { .api }
205
/**
206
* Set binary response type for browser environments
207
* @param {string} type - Response type: 'blob', 'arraybuffer' (browser only)
208
* @returns {Request} Request instance for chaining
209
*/
210
Request.prototype.responseType(type): Request;
211
212
/**
213
* Enable or disable response buffering
214
* @param {boolean} [enable=true] - Whether to buffer response
215
* @returns {Request} Request instance for chaining
216
*/
217
Request.prototype.buffer(enable?): Request;
218
219
/**
220
* Override response parser function
221
* @param {function} fn - Custom parser function
222
* @returns {Request} Request instance for chaining
223
*/
224
Request.prototype.parse(fn): Request;
225
226
/**
227
* Override request serializer function
228
* @param {function} fn - Custom serializer function
229
* @returns {Request} Request instance for chaining
230
*/
231
Request.prototype.serialize(fn): Request;
232
```
233
234
**Usage Examples:**
235
236
```javascript
237
// Set response type (browser)
238
superagent
239
.get('https://api.example.com/file.pdf')
240
.responseType('blob');
241
242
// Disable buffering for large responses
243
superagent
244
.get('https://api.example.com/large-file')
245
.buffer(false);
246
247
// Custom parser
248
superagent
249
.get('https://api.example.com/csv')
250
.parse((res, callback) => {
251
// Custom CSV parsing logic
252
const data = res.text.split('\n').map(line => line.split(','));
253
callback(null, data);
254
});
255
256
// Custom serializer
257
superagent
258
.post('https://api.example.com/data')
259
.serialize((obj) => {
260
// Custom serialization logic
261
return JSON.stringify(obj, null, 2);
262
});
263
```
264
265
### Advanced Request Options
266
267
Additional configuration options for specialized request handling.
268
269
```javascript { .api }
270
/**
271
* Set maximum response size in bytes
272
* @param {number} size - Maximum response size
273
* @returns {Request} Request instance for chaining
274
*/
275
Request.prototype.maxResponseSize(size): Request;
276
277
/**
278
* Configure redirect handling
279
* @param {number} count - Maximum number of redirects to follow
280
* @returns {Request} Request instance for chaining
281
*/
282
Request.prototype.redirects(count): Request;
283
284
/**
285
* Custom success condition function
286
* @param {function} fn - Function that returns true for successful responses
287
* @returns {Request} Request instance for chaining
288
*/
289
Request.prototype.ok(fn): Request;
290
291
/**
292
* Sort query parameters alphabetically
293
* @param {boolean} [enabled=true] - Whether to sort query parameters
294
* @returns {Request} Request instance for chaining
295
*/
296
Request.prototype.sortQuery(enabled?): Request;
297
```
298
299
**Usage Examples:**
300
301
```javascript
302
// Limit response size
303
superagent
304
.get('https://api.example.com/data')
305
.maxResponseSize(1024 * 1024); // 1MB limit
306
307
// Configure redirects
308
superagent
309
.get('https://api.example.com/redirect')
310
.redirects(3); // Follow up to 3 redirects
311
312
// Custom success condition
313
superagent
314
.get('https://api.example.com/data')
315
.ok(res => res.status < 500); // Treat 4xx as success
316
317
// Sort query parameters
318
superagent
319
.get('https://api.example.com/users')
320
.query({ z: 1, a: 2, m: 3 })
321
.sortQuery(); // Results in: ?a=2&m=3&z=1
322
```
323
324
### Browser & CORS Configuration
325
326
Configuration methods for browser environments and cross-origin requests.
327
328
```javascript { .api }
329
/**
330
* Enable cross-origin credentials (cookies, authorization headers, TLS client certificates)
331
* @param {boolean} [enabled=true] - Whether to send credentials with cross-origin requests
332
* @returns {Request} Request instance for chaining
333
*/
334
Request.prototype.withCredentials(enabled?): Request;
335
336
/**
337
* Use plugin or middleware function
338
* @param {function} fn - Plugin function that receives and modifies the request
339
* @returns {Request} Request instance for chaining
340
*/
341
Request.prototype.use(fn): Request;
342
```
343
344
**Usage Examples:**
345
346
```javascript
347
// Enable credentials for cross-origin requests
348
superagent
349
.get('https://api.example.com/private')
350
.withCredentials()
351
.set('Authorization', 'Bearer token');
352
353
// Disable credentials (default for cross-origin)
354
superagent
355
.get('https://api.example.com/public')
356
.withCredentials(false);
357
358
// Use plugin for request modification
359
function authPlugin(token) {
360
return (req) => {
361
req.set('Authorization', `Bearer ${token}`);
362
};
363
}
364
365
superagent
366
.get('https://api.example.com/data')
367
.use(authPlugin('my-token'));
368
369
// Multiple plugins can be chained
370
superagent
371
.get('https://api.example.com/data')
372
.use(authPlugin('token'))
373
.use((req) => {
374
req.set('User-Agent', 'MyApp/1.0');
375
});
376
```
377
378
### Request Serialization
379
380
Methods for converting the request to other formats.
381
382
```javascript { .api }
383
/**
384
* Return a JSON representation of the request
385
* @returns {object} JSON representation of the request
386
*/
387
Request.prototype.toJSON(): object;
388
```
389
390
**Usage Examples:**
391
392
```javascript
393
const request = superagent
394
.post('https://api.example.com/users')
395
.set('Authorization', 'Bearer token')
396
.send({ name: 'John' });
397
398
// Get JSON representation
399
const requestData = request.toJSON();
400
console.log(requestData);
401
// {
402
// method: 'POST',
403
// url: 'https://api.example.com/users',
404
// data: { name: 'John' },
405
// header: { Authorization: 'Bearer token' }
406
// }
407
```