0
# HTTP Client
1
2
Core HTTP client functionality for making web requests with support for all standard HTTP methods, custom headers, interceptors, and multiple client backends.
3
4
## Capabilities
5
6
### Main HTTP Function
7
8
Core HTTP function that accepts a configuration object and returns a Promise.
9
10
```javascript { .api }
11
/**
12
* Make an HTTP request with the specified options
13
* @param options - HTTP request configuration
14
* @returns Promise resolving to HttpResponse
15
*/
16
function $http(options: HttpOptions): Promise<HttpResponse>;
17
18
interface HttpOptions {
19
url?: string;
20
method?: string;
21
body?: any;
22
params?: any;
23
headers?: any;
24
before?(request: any): any;
25
progress?(event: ProgressEvent): void;
26
credentials?: boolean;
27
emulateHTTP?: boolean;
28
emulateJSON?: boolean;
29
timeout?: number;
30
responseType?: string;
31
withCredentials?: boolean;
32
crossOrigin?: boolean;
33
downloadProgress?(event: ProgressEvent): void;
34
uploadProgress?(event: ProgressEvent): void;
35
}
36
```
37
38
**Usage Examples:**
39
40
```javascript
41
// Basic request
42
this.$http({
43
url: '/api/users',
44
method: 'GET'
45
}).then(response => {
46
console.log(response.body);
47
});
48
49
// POST with body
50
this.$http({
51
url: '/api/users',
52
method: 'POST',
53
body: {name: 'John', email: 'john@example.com'}
54
}).then(response => {
55
console.log('Created:', response.body);
56
});
57
58
// With query parameters
59
this.$http({
60
url: '/api/users',
61
method: 'GET',
62
params: {page: 1, limit: 10}
63
}).then(response => {
64
console.log('Users:', response.body);
65
});
66
67
// With timeout and progress tracking
68
this.$http({
69
url: '/api/large-file',
70
method: 'POST',
71
body: formData,
72
timeout: 30000,
73
uploadProgress: (event) => {
74
if (event.lengthComputable) {
75
const percent = (event.loaded / event.total) * 100;
76
console.log(`Upload progress: ${percent.toFixed(2)}%`);
77
}
78
}
79
}).then(response => {
80
console.log('Upload complete:', response.body);
81
});
82
83
// With response type and credentials
84
this.$http({
85
url: '/api/document.pdf',
86
method: 'GET',
87
responseType: 'blob',
88
withCredentials: true
89
}).then(response => {
90
// response.body is a Blob
91
const url = URL.createObjectURL(response.body);
92
window.open(url);
93
});
94
```
95
96
### HTTP Method Shortcuts
97
98
Convenience methods for common HTTP operations.
99
100
```javascript { .api }
101
/**
102
* Perform GET request
103
* @param url - Request URL
104
* @param options - Additional options
105
* @returns Promise resolving to HttpResponse
106
*/
107
function $http.get(url: string, options?: HttpOptions): Promise<HttpResponse>;
108
109
/**
110
* Perform POST request
111
* @param url - Request URL
112
* @param body - Request body data
113
* @param options - Additional options
114
* @returns Promise resolving to HttpResponse
115
*/
116
function $http.post(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;
117
118
/**
119
* Perform PUT request
120
* @param url - Request URL
121
* @param body - Request body data
122
* @param options - Additional options
123
* @returns Promise resolving to HttpResponse
124
*/
125
function $http.put(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;
126
127
/**
128
* Perform PATCH request
129
* @param url - Request URL
130
* @param body - Request body data
131
* @param options - Additional options
132
* @returns Promise resolving to HttpResponse
133
*/
134
function $http.patch(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;
135
136
/**
137
* Perform DELETE request
138
* @param url - Request URL
139
* @param options - Additional options
140
* @returns Promise resolving to HttpResponse
141
*/
142
function $http.delete(url: string, options?: HttpOptions): Promise<HttpResponse>;
143
144
/**
145
* Perform HEAD request
146
* @param url - Request URL
147
* @param options - Additional options
148
* @returns Promise resolving to HttpResponse
149
*/
150
function $http.head(url: string, options?: HttpOptions): Promise<HttpResponse>;
151
152
/**
153
* Perform JSONP request
154
* @param url - Request URL
155
* @param options - Additional options
156
* @returns Promise resolving to HttpResponse
157
*/
158
function $http.jsonp(url: string, options?: HttpOptions): Promise<HttpResponse>;
159
```
160
161
**Usage Examples:**
162
163
```javascript
164
// GET request
165
this.$http.get('/api/users').then(response => {
166
console.log(response.body);
167
});
168
169
// POST request
170
this.$http.post('/api/users', {
171
name: 'John',
172
email: 'john@example.com'
173
}).then(response => {
174
console.log('Created user:', response.body);
175
});
176
177
// PUT request with options
178
this.$http.put('/api/users/1', userData, {
179
headers: {'Authorization': 'Bearer token'}
180
}).then(response => {
181
console.log('Updated user:', response.body);
182
});
183
184
// DELETE request
185
this.$http.delete('/api/users/1').then(response => {
186
console.log('User deleted');
187
});
188
189
// JSONP request
190
this.$http.jsonp('/api/external-data').then(response => {
191
console.log('JSONP data:', response.body);
192
});
193
```
194
195
### HTTP Response
196
197
Object representing the HTTP response with data access methods and metadata.
198
199
```javascript { .api }
200
interface HttpResponse {
201
/** Response data (getter/setter alias for body) */
202
data: any;
203
/** Response body (actual response content) */
204
body: any;
205
/** Raw response text (when response is string) */
206
bodyText?: string;
207
/** Raw response blob (when response is Blob) */
208
bodyBlob?: Blob;
209
/** Whether the response was successful (status 200-299) */
210
ok: boolean;
211
/** HTTP status code */
212
status: number;
213
/** HTTP status text */
214
statusText: string;
215
/** Request URL */
216
url: string;
217
/** Headers object with methods for header access */
218
headers: Headers;
219
/** Get response as text string */
220
text(): Promise<string>;
221
/** Parse response as JSON */
222
json(): Promise<any>;
223
/** Get response as Blob (browser only) */
224
blob(): Promise<Blob>;
225
}
226
```
227
228
**Usage Examples:**
229
230
```javascript
231
this.$http.get('/api/users').then(response => {
232
console.log('Status:', response.status);
233
console.log('OK:', response.ok);
234
console.log('Data:', response.body);
235
console.log('Content-Type:', response.headers.get('content-type'));
236
237
// Access raw text (returns Promise)
238
response.text().then(text => console.log('Raw text:', text));
239
240
// Parse as JSON (if not auto-parsed, returns Promise)
241
response.json().then(jsonData => console.log('JSON data:', jsonData));
242
});
243
```
244
245
### Global Configuration
246
247
Configure default options, headers, and interceptors for all HTTP requests.
248
249
```javascript { .api }
250
// Default options
251
Vue.http.options: HttpOptions & { root: string };
252
253
// Default headers for different HTTP methods
254
Vue.http.headers: HttpHeaders;
255
256
interface HttpHeaders {
257
put?: { [key: string]: string };
258
post?: { [key: string]: string };
259
patch?: { [key: string]: string };
260
delete?: { [key: string]: string };
261
common?: { [key: string]: string };
262
custom?: { [key: string]: string };
263
[key: string]: any;
264
}
265
266
// Interceptor management
267
Vue.http.interceptors: (HttpInterceptor | string)[];
268
Vue.http.interceptor: { [name: string]: HttpInterceptor };
269
```
270
271
**Usage Examples:**
272
273
```javascript
274
// Set root URL for all requests
275
Vue.http.options.root = 'https://api.example.com';
276
277
// Set default headers
278
Vue.http.headers.common['Authorization'] = 'Bearer ' + token;
279
Vue.http.headers.post['Content-Type'] = 'application/json';
280
281
// Custom headers
282
Vue.http.headers.custom['X-API-Key'] = 'your-api-key';
283
284
// Add interceptor
285
Vue.http.interceptors.push(function(request, next) {
286
console.log('Sending request to:', request.url);
287
next();
288
});
289
```
290
291
### Error Handling
292
293
HTTP client automatically rejects promises for non-successful status codes and network errors.
294
295
**Usage Examples:**
296
297
```javascript
298
this.$http.get('/api/users').then(response => {
299
// Success (status 200-299)
300
console.log('Users:', response.body);
301
}, response => {
302
// Error (status >= 400 or network error)
303
console.error('Error:', response.status, response.statusText);
304
console.error('Error body:', response.body);
305
});
306
307
// Using async/await with try/catch
308
async function fetchUsers() {
309
try {
310
const response = await this.$http.get('/api/users');
311
console.log('Users:', response.body);
312
} catch (response) {
313
console.error('Error:', response.status, response.statusText);
314
}
315
}
316
```
317
318
## Types
319
320
```javascript { .api }
321
interface HttpOptions {
322
/** URL for the request */
323
url?: string;
324
/** HTTP method (GET, POST, PUT, etc.) */
325
method?: string;
326
/** Request body data */
327
body?: any;
328
/** URL query parameters */
329
params?: any;
330
/** Request headers */
331
headers?: any;
332
/** Pre-request callback */
333
before?(request: any): any;
334
/** Progress callback (deprecated - use downloadProgress/uploadProgress) */
335
progress?(event: ProgressEvent): void;
336
/** Include credentials in cross-origin requests */
337
credentials?: boolean;
338
/** Emulate HTTP methods using POST with _method parameter */
339
emulateHTTP?: boolean;
340
/** Send data as form-encoded instead of JSON */
341
emulateJSON?: boolean;
342
/** Request timeout in milliseconds */
343
timeout?: number;
344
/** Expected response type (arraybuffer, blob, document, json, text) */
345
responseType?: string;
346
/** Include credentials in cross-origin requests (alias for credentials) */
347
withCredentials?: boolean;
348
/** Whether request is cross-origin (affects X-Requested-With header) */
349
crossOrigin?: boolean;
350
/** Download progress callback for GET requests */
351
downloadProgress?(event: ProgressEvent): void;
352
/** Upload progress callback for POST/PUT requests */
353
uploadProgress?(event: ProgressEvent): void;
354
}
355
356
interface HttpHeaders {
357
/** Headers for PUT requests */
358
put?: { [key: string]: string };
359
/** Headers for POST requests */
360
post?: { [key: string]: string };
361
/** Headers for PATCH requests */
362
patch?: { [key: string]: string };
363
/** Headers for DELETE requests */
364
delete?: { [key: string]: string };
365
/** Headers for all requests */
366
common?: { [key: string]: string };
367
/** Custom headers */
368
custom?: { [key: string]: string };
369
/** Additional method-specific headers */
370
[key: string]: any;
371
}
372
373
interface Headers {
374
/** Internal header storage map (normalized names -> array of values) */
375
map: { [normalizedName: string]: string[] };
376
/** Check if header exists (case-insensitive lookup) */
377
has(name: string): boolean;
378
/** Get header value (comma-separated if multiple values) */
379
get(name: string): string | null;
380
/** Get all values for a header as array */
381
getAll(name: string): string[];
382
/** Set header value (replaces all existing values) */
383
set(name: string, value: string): void;
384
/** Add header value (appends to existing values) */
385
append(name: string, value: string): void;
386
/** Delete header by name (case-insensitive) */
387
delete(name: string): void;
388
/** Delete all headers */
389
deleteAll(): void;
390
/** Iterate over all header values (calls callback for each value) */
391
forEach(callback: (value: string, name: string, headers: Headers) => void, thisArg?: any): void;
392
}
393
```