Chapter 3
Dealing with HTTP responses
A request can either succeed or fail and AngularJS provides two methods to register
callbacks to deal with the two outcomes: success and error. Both the methods
accept a callback function that will be called with the following parameters:
- data: The actual response data
- status: The HTTP status of the response
- headers: A function giving access to the HTTP response headers
- config: The configuration object that was supplied when a request
was triggered
AngularJS will invoke success callbacks for the HTTP responses with
status ranging from 200 to 299. Responses with a status outside of this
range will trigger the error callback. The redirection responses (HTTP
status 3xx codes) are automatically followed by a browser.
Both success and error callbacks are optional. If we don't register any callback a
response will be silently ignored.
Response data conversion
As with request data conversions, the $http service will try to convert responses
containing a JSON string into a JavaScript object. This conversion happens
before invoking success or error callbacks. The default conversion behavior
can be customized.
In the current version of AngularJS the $http service will try to
perform JSON string to JavaScript object conversion on any responses
that look like JSON (that is, starts with { or [ and end with ] or }).
Dealing with same-origin policy restrictions
Web browsers enforce the same-origin security policy. This policy authorizes XHR
interactions only with resources originating from the same source (defined as a
combination of a protocol, host and its port) and enforces restrictions on interactions
with "foreign" resources.