forked from angular/code.angularjs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathng.$http.html
514 lines (498 loc) · 32.7 KB
/
ng.$http.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<a href="http://github.com/angular/angular.js/tree/v1.2.3/src/ng/http.js#L173" class="view-source btn btn-action"><i class="icon-zoom-in"> </i> View source</a><a href="http://github.com/angular/angular.js/edit/master/src/ng/http.js" class="improve-docs btn btn-primary"><i class="icon-edit"> </i> Improve this doc</a><h1><code ng:non-bindable="">$http</code>
<div><span class="hint">service in module <code ng:non-bindable="">ng</code>
</span>
</div>
</h1>
<div><h2 id="description">Description</h2>
<div class="description"><div class="ng-http-page"><p>The <code>$http</code> service is a core Angular service that facilitates communication with the remote
HTTP servers via the browser's <a href="https://developer.mozilla.org/en/xmlhttprequest">XMLHttpRequest</a> object or via <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a>.</p>
<p>For unit testing applications that use <code>$http</code> service, see
<a href="api/ngMock.$httpBackend">$httpBackend mock</a>.</p>
<p>For a higher level of abstraction, please check out the <a href="api/ngResource.$resource">$resource</a> service.</p>
<p>The $http API is based on the <a href="api/ng.$q"><code>deferred/promise APIs</code></a> exposed by
the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
it is important to familiarize yourself with these APIs and the guarantees they provide.</p>
<h3 id="description_general-usage">General usage</h3>
<p>The <code>$http</code> service is a function which takes a single argument — a configuration object —
that is used to generate an HTTP request and returns a <a href="api/ng.$q"><code>promise</code></a>
with two $http specific methods: <code>success</code> and <code>error</code>.</p>
<pre class="prettyprint linenums">
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
</pre>
<p>Since the returned value of calling the $http function is a <code>promise</code>, you can also use
the <code>then</code> method to register callbacks, and these callbacks will receive a single argument –
an object representing the response. See the API signature and type info below for more
details.</p>
<p>A response status code between 200 and 299 is considered a success status and
will result in the success callback being called. Note that if the response is a redirect,
XMLHttpRequest will transparently follow it, meaning that the error callback will not be
called for such responses.</p>
<h3 id="description_calling-$http-from-outside-angularjs">Calling $http from outside AngularJS</h3>
<p>The <code>$http</code> service will not actually send the request until the next <code>$digest()</code> is
executed. Normally this is not an issue, since almost all the time your call to <code>$http</code> will
be from within a <code>$apply()</code> block.
If you are calling <code>$http</code> from outside Angular, then you should wrap it in a call to
<code>$apply</code> to cause a $digest to occur and also to handle errors in the block correctly.</p>
<pre><code>$scope.$apply(function() {
$http(...);
});</code></pre>
<h3 id="description_writing-unit-tests-that-use-$http">Writing Unit Tests that use $http</h3>
<p>When unit testing you are mostly responsible for scheduling the <code>$digest</code> cycle. If you do
not trigger a <code>$digest</code> before calling <code>$httpBackend.flush()</code> then the request will not have
been made and <code>$httpBackend.expect(...)</code> expectations will fail. The solution is to run the
code that calls the <code>$http()</code> method inside a $apply block as explained in the previous
section.</p>
<pre><code>$httpBackend.expectGET(...);
$scope.$apply(function() {
$http.get(...);
});
$httpBackend.flush();</code></pre>
<h3 id="description_shortcut-methods">Shortcut methods</h3>
<p>Since all invocations of the $http service require passing in an HTTP method and URL, and
POST/PUT requests require request data to be provided as well, shortcut methods
were created:</p>
<pre class="prettyprint linenums">
$http.get('/someUrl').success(successCallback);
$http.post('/someUrl', data).success(successCallback);
</pre>
<p>Complete list of shortcut methods:</p>
<ul>
<li><a href="api/ng.$http#methods_get"><code>$http.get</code></a></li>
<li><a href="api/ng.$http#methods_head"><code>$http.head</code></a></li>
<li><a href="api/ng.$http#methods_post"><code>$http.post</code></a></li>
<li><a href="api/ng.$http#methods_put"><code>$http.put</code></a></li>
<li><a href="api/ng.$http#methods_delete"><code>$http.delete</code></a></li>
<li><a href="api/ng.$http#methods_jsonp"><code>$http.jsonp</code></a></li>
</ul>
<h3 id="description_setting-http-headers">Setting HTTP Headers</h3>
<p>The $http service will automatically add certain HTTP headers to all requests. These defaults
can be fully configured by accessing the <code>$httpProvider.defaults.headers</code> configuration
object, which currently contains this default configuration:</p>
<ul>
<li><code>$httpProvider.defaults.headers.common</code> (headers that are common for all requests):<ul>
<li><code>Accept: application/json, text/plain, * / *</code></li>
</ul>
</li>
<li><code>$httpProvider.defaults.headers.post</code>: (header defaults for POST requests)<ul>
<li><code>Content-Type: application/json</code></li>
</ul>
</li>
<li><code>$httpProvider.defaults.headers.put</code> (header defaults for PUT requests)<ul>
<li><code>Content-Type: application/json</code></li>
</ul>
</li>
</ul>
<p>To add or overwrite these defaults, simply add or remove a property from these configuration
objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
with the lowercased HTTP method name as the key, e.g.
`$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.</p>
<p>The defaults can also be set at runtime via the <code>$http.defaults</code> object in the same
fashion. In addition, you can supply a <code>headers</code> property in the config object passed when
calling <code>$http(config)</code>, which overrides the defaults without changing them globally.</p>
<h3 id="description_transforming-requests-and-responses">Transforming Requests and Responses</h3>
<p>Both requests and responses can be transformed using transform functions. By default, Angular
applies these transformations:</p>
<p>Request transformations:</p>
<ul>
<li>If the <code>data</code> property of the request configuration object contains an object, serialize it
into JSON format.</li>
</ul>
<p>Response transformations:</p>
<ul>
<li>If XSRF prefix is detected, strip it (see Security Considerations section below).</li>
<li>If JSON response is detected, deserialize it using a JSON parser.</li>
</ul>
<p>To globally augment or override the default transforms, modify the
<code>$httpProvider.defaults.transformRequest</code> and <code>$httpProvider.defaults.transformResponse</code>
properties. These properties are by default an array of transform functions, which allows you
to <code>push</code> or <code>unshift</code> a new transformation function into the transformation chain. You can
also decide to completely override any default transformations by assigning your
transformation functions to these properties directly without the array wrapper.</p>
<p>Similarly, to locally override the request/response transforms, augment the
<code>transformRequest</code> and/or <code>transformResponse</code> properties of the configuration object passed
into <code>$http</code>.</p>
<h3 id="description_caching">Caching</h3>
<p>To enable caching, set the request configuration <code>cache</code> property to <code>true</code> (to use default
cache) or to a custom cache object (built with <a href="api/ng.$cacheFactory"><code><code>$cacheFactory</code></code></a>).
When the cache is enabled, <code>$http</code> stores the response from the server in the specified
cache. The next time the same request is made, the response is served from the cache without
sending a request to the server.</p>
<p>Note that even if the response is served from cache, delivery of the data is asynchronous in
the same way that real requests are.</p>
<p>If there are multiple GET requests for the same URL that should be cached using the same
cache, but the cache is not populated yet, only one request to the server will be made and
the remaining requests will be fulfilled using the response from the first request.</p>
<p>You can change the default cache to a new object (built with
<a href="api/ng.$cacheFactory"><code><code>$cacheFactory</code></code></a>) by updating the
<a href="api/ng.$http#properties_defaults"><code><code>$http.defaults.cache</code></code></a> property. All requests who set
their <code>cache</code> property to <code>true</code> will now use this cache object.</p>
<p>If you set the default cache to <code>false</code> then only requests that specify their own custom
cache object will be cached.</p>
<h3 id="description_interceptors">Interceptors</h3>
<p>Before you start creating interceptors, be sure to understand the
<a href="api/ng.$q"><code>$q and deferred/promise APIs</code></a>.</p>
<p>For purposes of global error handling, authentication, or any kind of synchronous or
asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
able to intercept requests before they are handed to the server and
responses before they are handed over to the application code that
initiated these requests. The interceptors leverage the <a href="api/ng.$q"><code>promise APIs</code></a> to fulfill this need for both synchronous and asynchronous pre-processing.</p>
<p>The interceptors are service factories that are registered with the <code>$httpProvider</code> by
adding them to the <code>$httpProvider.interceptors</code> array. The factory is called and
injected with dependencies (if specified) and returns the interceptor.</p>
<p>There are two kinds of interceptors (and two kinds of rejection interceptors):</p>
<ul>
<li><code>request</code>: interceptors get called with http <code>config</code> object. The function is free to
modify the <code>config</code> or create a new one. The function needs to return the <code>config</code>
directly or as a promise.</li>
<li><code>requestError</code>: interceptor gets called when a previous interceptor threw an error or
resolved with a rejection.</li>
<li><code>response</code>: interceptors get called with http <code>response</code> object. The function is free to
modify the <code>response</code> or create a new one. The function needs to return the <code>response</code>
directly or as a promise.</li>
<li><code>responseError</code>: interceptor gets called when a previous interceptor threw an error or
resolved with a rejection.</li>
</ul>
<pre class="prettyprint linenums">
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config || $q.when(config);
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response || $q.when(response);
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
// register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
};
});
</pre>
<h3 id="description_response-interceptors">Response interceptors (DEPRECATED)</h3>
<p>Before you start creating interceptors, be sure to understand the
<a href="api/ng.$q"><code>$q and deferred/promise APIs</code></a>.</p>
<p>For purposes of global error handling, authentication or any kind of synchronous or
asynchronous preprocessing of received responses, it is desirable to be able to intercept
responses for http requests before they are handed over to the application code that
initiated these requests. The response interceptors leverage the <a href="api/ng.$q"><code>promise apis</code></a> to fulfil this need for both synchronous and asynchronous preprocessing.</p>
<p>The interceptors are service factories that are registered with the $httpProvider by
adding them to the <code>$httpProvider.responseInterceptors</code> array. The factory is called and
injected with dependencies (if specified) and returns the interceptor — a function that
takes a <a href="api/ng.$q"><code>promise</code></a> and returns the original or a new promise.</p>
<pre class="prettyprint linenums">
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return function(promise) {
return promise.then(function(response) {
// do something on success
return response;
}, function(response) {
// do something on error
if (canRecover(response)) {
return responseOrNewPromise
}
return $q.reject(response);
});
}
});
$httpProvider.responseInterceptors.push('myHttpInterceptor');
// register the interceptor via an anonymous factory
$httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
return function(promise) {
// same as above
}
});
</pre>
<h3 id="description_security-considerations">Security Considerations</h3>
<p>When designing web applications, consider security threats from:</p>
<ul>
<li><a href="http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx">JSON vulnerability</a></li>
<li><a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">XSRF</a></li>
</ul>
<p>Both server and the client must cooperate in order to eliminate these threats. Angular comes
pre-configured with strategies that address these issues, but for this to work backend server
cooperation is required.</p>
<h4 id="description_security-considerations_json-vulnerability-protection">JSON Vulnerability Protection</h4>
<p>A <a href="http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx">JSON vulnerability</a> allows third party website to turn your JSON resource URL into
<a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a> request under some conditions. To
counter this your server can prefix all JSON requests with following string <code>")]}',\n"</code>.
Angular will automatically strip the prefix before processing it as JSON.</p>
<p>For example if your server needs to return:
<pre class="prettyprint linenums">
['one','two']
</pre>
<p>which is vulnerable to attack, your server can return:
<pre class="prettyprint linenums">
)]}',
['one','two']
</pre>
<p>Angular will strip the prefix, before processing the JSON.</p>
<h4 id="description_security-considerations_cross-site-request-forgery-protection">Cross Site Request Forgery (XSRF) Protection</h4>
<p><a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">XSRF</a> is a technique by which
an unauthorized site can gain your user's private data. Angular provides a mechanism
to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
(by default, <code>XSRF-TOKEN</code>) and sets it as an HTTP header (<code>X-XSRF-TOKEN</code>). Since only
JavaScript that runs on your domain could read the cookie, your server can be assured that
the XHR came from JavaScript running on your domain. The header will not be set for
cross-domain requests.</p>
<p>To take advantage of this, your server needs to set a token in a JavaScript readable session
cookie called <code>XSRF-TOKEN</code> on the first HTTP GET request. On subsequent XHR requests the
server can verify that the cookie matches <code>X-XSRF-TOKEN</code> HTTP header, and therefore be sure
that only JavaScript running on your domain could have sent the request. The token must be
unique for each user and must be verifiable by the server (to prevent the JavaScript from
making up its own tokens). We recommend that the token is a digest of your site's
authentication cookie with a <a href="https://en.wikipedia.org/wiki/Salt_(cryptography)">salt</a>
for added security.</p>
<p>The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
properties of either $httpProvider.defaults, or the per-request config object.</p>
</div></div>
<h2 id="dependencies">Dependencies</h2>
<ul class="dependencies"><li><code ng:non-bindable=""><a href="api/ng.$httpBackend">$httpBackend</a></code>
</li>
<li><code ng:non-bindable=""><a href="api/ng.$browser">$browser</a></code>
</li>
<li><code ng:non-bindable=""><a href="api/ng.$cacheFactory">$cacheFactory</a></code>
</li>
<li><code ng:non-bindable=""><a href="api/ng.$rootScope">$rootScope</a></code>
</li>
<li><code ng:non-bindable=""><a href="api/ng.$q">$q</a></code>
</li>
<li><code ng:non-bindable=""><a href="api/ng.$injector">$injector</a></code>
</li>
</ul>
<h2 id="usage">Usage</h2>
<div class="usage"><pre class="prettyprint linenums">$http(config);</pre>
<h4 id="usage_parameters">Parameters</h4><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>config</td><td><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ng-http-page"><p>Object describing the request to be made and how it should be
processed. The object has following properties:</p>
<ul>
<li><strong>method</strong> – <code>{string}</code> – HTTP method (e.g. 'GET', 'POST', etc)</li>
<li><strong>url</strong> – <code>{string}</code> – Absolute or relative URL of the resource that is being requested.</li>
<li><strong>params</strong> – <code>{Object.<string|Object>}</code> – Map of strings or objects which will be turned
to <code>?key1=value1&key2=value2</code> after the url. If the value is not a string, it will be
JSONified.</li>
<li><strong>data</strong> – <code>{string|Object}</code> – Data to be sent as the request message data.</li>
<li><strong>headers</strong> – <code>{Object}</code> – Map of strings or functions which return strings representing
HTTP headers to send to the server. If the return value of a function is null, the
header will not be sent.</li>
<li><strong>xsrfHeaderName</strong> – <code>{string}</code> – Name of HTTP header to populate with the XSRF token.</li>
<li><strong>xsrfCookieName</strong> – <code>{string}</code> – Name of cookie containing the XSRF token.</li>
<li><strong>transformRequest</strong> –
<code>{function(data, headersGetter)|Array.<function(data, headersGetter)>}</code> –
transform function or an array of such functions. The transform function takes the http
request body and headers and returns its transformed (typically serialized) version.</li>
<li><strong>transformResponse</strong> –
<code>{function(data, headersGetter)|Array.<function(data, headersGetter)>}</code> –
transform function or an array of such functions. The transform function takes the http
response body and headers and returns its transformed (typically deserialized) version.</li>
<li><strong>cache</strong> – <code>{boolean|Cache}</code> – If true, a default $http cache will be used to cache the
GET request, otherwise if a cache instance built with
<a href="api/ng.$cacheFactory"><code>$cacheFactory</code></a>, this cache will be used for
caching.</li>
<li><strong>timeout</strong> – <code>{number|Promise}</code> – timeout in milliseconds, or <a href="api/ng.$q"><code>promise</code></a>
that should abort the request when resolved.</li>
<li><strong>withCredentials</strong> - <code>{boolean}</code> - whether to to set the <code>withCredentials</code> flag on the
XHR object. See <a href="https://developer.mozilla.org/en/http_access_control#section_5">requests with credentials</a> for more information.</li>
<li><strong>responseType</strong> - <code>{string}</code> - see <a href="https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType">requestType</a>.</li>
</ul>
</div></td></tr></tbody></table><h4 id="usage_returns">Returns</h4><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-page"><p>Returns a <a href="api/ng.$q"><code>promise</code></a> object with the
standard <code>then</code> method and two http specific methods: <code>success</code> and <code>error</code>. The <code>then</code>
method takes two arguments a success and an error callback which will be called with a
response object. The <code>success</code> and <code>error</code> methods take a single argument - a function that
will be called when the request succeeds or fails respectively. The arguments passed into
these functions are destructured representation of the response object passed into the
<code>then</code> method. The response object has these properties:</p>
<ul>
<li><strong>data</strong> – <code>{string|Object}</code> – The response body transformed with the transform
functions.</li>
<li><strong>status</strong> – <code>{number}</code> – HTTP status code of the response.</li>
<li><strong>headers</strong> – <code>{function([headerName])}</code> – Header getter function.</li>
<li><strong>config</strong> – <code>{Object}</code> – The configuration object that was used to generate the request.</li>
</ul>
</div></td></tr></table></div>
<div class="member method"><h2 id="methods">Methods</h2>
<ul class="methods"><li><h3 id="methods_delete">delete(url, config)</h3>
<div class="delete"><div class="ng-http-delete-page"><p>Shortcut method to perform <code>DELETE</code> request.</p>
</div><h5 id="methods_delete_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-http-delete-page"><p>Relative or absolute URL specifying the destination of the request</p>
</div></td></tr><tr><td>config <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ng-http-delete-page"><p>Optional configuration object</p>
</div></td></tr></tbody></table><h5 id="methods_delete_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-delete-page"><p>Future object</p>
</div></td></tr></table></div>
</li>
<li><h3 id="methods_get">get(url, config)</h3>
<div class="get"><div class="ng-http-get-page"><p>Shortcut method to perform <code>GET</code> request.</p>
</div><h5 id="methods_get_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-http-get-page"><p>Relative or absolute URL specifying the destination of the request</p>
</div></td></tr><tr><td>config <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ng-http-get-page"><p>Optional configuration object</p>
</div></td></tr></tbody></table><h5 id="methods_get_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-get-page"><p>Future object</p>
</div></td></tr></table></div>
</li>
<li><h3 id="methods_head">head(url, config)</h3>
<div class="head"><div class="ng-http-head-page"><p>Shortcut method to perform <code>HEAD</code> request.</p>
</div><h5 id="methods_head_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-http-head-page"><p>Relative or absolute URL specifying the destination of the request</p>
</div></td></tr><tr><td>config <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ng-http-head-page"><p>Optional configuration object</p>
</div></td></tr></tbody></table><h5 id="methods_head_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-head-page"><p>Future object</p>
</div></td></tr></table></div>
</li>
<li><h3 id="methods_jsonp">jsonp(url, config)</h3>
<div class="jsonp"><div class="ng-http-jsonp-page"><p>Shortcut method to perform <code>JSONP</code> request.</p>
</div><h5 id="methods_jsonp_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-http-jsonp-page"><p>Relative or absolute URL specifying the destination of the request.
Should contain <code>JSON_CALLBACK</code> string.</p>
</div></td></tr><tr><td>config <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ng-http-jsonp-page"><p>Optional configuration object</p>
</div></td></tr></tbody></table><h5 id="methods_jsonp_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-jsonp-page"><p>Future object</p>
</div></td></tr></table></div>
</li>
<li><h3 id="methods_post">post(url, data, config)</h3>
<div class="post"><div class="ng-http-post-page"><p>Shortcut method to perform <code>POST</code> request.</p>
</div><h5 id="methods_post_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-http-post-page"><p>Relative or absolute URL specifying the destination of the request</p>
</div></td></tr><tr><td>data</td><td><a href="" class="label type-hint type-hint-object">*</a></td><td><div class="ng-http-post-page"><p>Request content</p>
</div></td></tr><tr><td>config <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ng-http-post-page"><p>Optional configuration object</p>
</div></td></tr></tbody></table><h5 id="methods_post_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-post-page"><p>Future object</p>
</div></td></tr></table></div>
</li>
<li><h3 id="methods_put">put(url, data, config)</h3>
<div class="put"><div class="ng-http-put-page"><p>Shortcut method to perform <code>PUT</code> request.</p>
</div><h5 id="methods_put_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a></td><td><div class="ng-http-put-page"><p>Relative or absolute URL specifying the destination of the request</p>
</div></td></tr><tr><td>data</td><td><a href="" class="label type-hint type-hint-object">*</a></td><td><div class="ng-http-put-page"><p>Request content</p>
</div></td></tr><tr><td>config <div><em>(optional)</em></div></td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ng-http-put-page"><p>Optional configuration object</p>
</div></td></tr></tbody></table><h5 id="methods_put_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-httppromise">HttpPromise</a></td><td><div class="ng-http-put-page"><p>Future object</p>
</div></td></tr></table></div>
</li>
</ul>
</div>
<div class="member property"><h2 id="properties">Properties</h2>
<ul class="properties"><li><h3 id="properties_defaults">defaults</h3>
<div class="defaults"><div class="ng-http-defaults-page"><p>Runtime equivalent of the <code>$httpProvider.defaults</code> property. Allows configuration of
default headers, withCredentials as well as request and response transformations.</p>
<p>See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.</p>
</div></div>
</li>
<li><h3 id="properties_pendingrequests">pendingRequests</h3>
<div class="pendingrequests"><div class="ng-http-page"><p>Array of config objects for currently pending
requests. This is primarily meant to be used for debugging purposes.</p>
</div></div>
</li>
</ul>
</div>
<h2 id="example">Example</h2>
<div class="example"><div class="ng-http-page"><h4 id="example_source">Source</h4>
<div source-edit="" source-edit-deps="angular.js script.js" source-edit-html="index.html-138 http-hello.html" source-edit-css="" source-edit-js="script.js-139" source-edit-json="" source-edit-unit="" source-edit-scenario="scenario.js-140"></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-138" ng-html-wrap=" angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-138">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button
ng-click="updateModel('JSONP',
'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button
ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</script>
</div>
<div class="tab-pane" title="http-hello.html">
<pre class="prettyprint linenums" ng-set-text="http-hello.html"></pre>
<script type="text/ng-template" id="http-hello.html">
Hello, $http!
</script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-139"></pre>
<script type="text/ng-template" id="script.js-139">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</script>
</div>
<div class="tab-pane" title="End to end test">
<pre class="prettyprint linenums" ng-set-text="scenario.js-140"></pre>
<script type="text/ng-template" id="scenario.js-140">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</script>
</div>
</div><h4 id="example_demo">Demo</h4>
<div class="well doc-example-live animate-container" ng-embed-app="" ng-set-html="index.html-138" ng-eval-javascript="script.js-139"></div>
</div></div>
</div>