Improve this Doc  View Source


  1. - $httpProvider
  2. - service in module ng


The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

For unit testing applications that use $http service, see $httpBackend mock.

For a higher level of abstraction, please check out the $resource service.

The $http API is based on the deferred/promise APIs 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.

General usage

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise that is resolved (request success) or rejected (request failure) with a response object.

// Simple GET request example:
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.

Shortcut methods

Shortcut methods are also available. All shortcut methods require passing in the URL, and request data must be passed in for POST/PUT requests. An optional config can be passed as the last argument.

$http.get('/someUrl', config).then(successCallback, errorCallback);
$'/someUrl', data, config).then(successCallback, errorCallback);

Complete list of shortcut methods:

Writing Unit Tests that use $http

When unit testing (using ngMock), it is necessary to call $httpBackend.flush() to flush each pending request using trained responses.


Setting HTTP Headers

The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

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' }.

The defaults can also be set at runtime via the $http.defaults object in the same fashion. For example:$http) {
  $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';

In addition, you can supply a headers property in the config object passed when calling $http(config), which overrides the defaults without changing them globally.

To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, Use the headers property, setting the desired header to undefined. For example:

var req = {
 method: 'POST',
 url: '',
 headers: {
   'Content-Type': undefined
 data: { test: 'test' }

$http(req).then(function(){...}, function(){...});

Transforming Requests and Responses

Both requests and responses can be transformed using transformation functions: transformRequest and transformResponse. These properties can be a single function that returns the transformed value (function(data, headersGetter, status)) or an array of such transformation functions, which allows you to push or unshift a new transformation function into the transformation chain.

Note: AngularJS does not make a copy of the data parameter before it is passed into the transformRequest pipeline. That means changes to the properties of data are not local to the transform function (since Javascript passes objects by reference). For example, when calling $http.get(url, $scope.myObject), modifications to the object's properties in a transformRequest function will be reflected on the scope and in any templates where the object is data-bound. To prevent this, transform functions should have no side-effects. If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.

Default Transformations

The $httpProvider provider and $http service expose defaults.transformRequest and defaults.transformResponse properties. If a request does not provide its own transformations then these will be applied.

You can augment or replace the default transformations by modifying these properties by adding to or replacing the array.

AngularJS provides the following default transformations:

Request transformations ($httpProvider.defaults.transformRequest and $http.defaults.transformRequest) is an array with one function that does the following:

Response transformations ($httpProvider.defaults.transformResponse and $http.defaults.transformResponse) is an array with one function that does the following:

Overriding the Default Transformations Per Request

If you wish to override the request/response transformations only for a single request then provide transformRequest and/or transformResponse properties on the configuration object passed into $http.

Note that if you provide these properties on the config object the default transformations will be overwritten. If you wish to augment the default transformations then you must include them in your local transformation array.

The following code demonstrates adding a new response transformation to be run after the default response transformations have been run.

function appendTransform(defaults, transform) {

  // We can't guarantee that the default transformation is an array
  defaults = angular.isArray(defaults) ? defaults : [defaults];

  // Append the new transformation to the defaults
  return defaults.concat(transform);

  url: '...',
  method: 'GET',
  transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
    return doTransform(value);


$http responses are not cached by default. To enable caching, you must set the config.cache value or the default cache value to TRUE or to a cache object (created with $cacheFactory). If defined, the value of config.cache takes precedence over the default cache value.

In order to:

If caching is enabled, but neither the default cache nor config.cache are set to a cache object, then the default $cacheFactory("$http") object is used.

The default cache value can be set by updating the $http.defaults.cache property or the $httpProvider.defaults.cache property.

When caching is enabled, $http stores the response from the server using the relevant cache object. The next time the same request is made, the response is returned from the cache without sending a request to the server.

Take note that:


Before you start creating interceptors, be sure to understand the $q and deferred/promise APIs.

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 promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

There are two kinds of interceptors (and two kinds of rejection interceptors):

// 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;

    // 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;

    // optional method
   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      return $q.reject(rejection);


// alternatively, 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

Security Considerations

When designing web applications, consider security threats from:

Both server and the client must cooperate in order to eliminate these threats. AngularJS comes pre-configured with strategies that address these issues, but for this to work backend server cooperation is required.

JSON Vulnerability Protection

A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". AngularJS will automatically strip the prefix before processing it as JSON.

For example if your server needs to return:


which is vulnerable to attack, your server can return:


AngularJS will strip the prefix, before processing the JSON.

Cross Site Request Forgery (XSRF) Protection

XSRF is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (by default X-XSRF-TOKEN). 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.

To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on the first HTTP GET request. On subsequent XHR requests the server can verify that the cookie matches the X-XSRF-TOKEN 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 salt for added security.

The header will — by default — not be set for cross-domain requests. This prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you want to, you can whitelist additional origins to also receive the XSRF token, by adding them to xsrfWhitelistedOrigins. This might be useful, for example, if your application, served from, needs to access your API at See $httpProvider.xsrfWhitelistedOrigins for more details.

Only whitelist origins that you have control over and make sure you understand the implications of doing so.

The name of the cookie and the header can be specified using the xsrfCookieName and xsrfHeaderName properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, or the per-request config object.

In order to prevent collisions in environments where multiple AngularJS apps share the same domain or subdomain, we recommend that each application uses a unique cookie name.





Param Type Details
config object

Object describing the request to be made and how it should be processed. The object has following properties:

  • method{string} – HTTP method (e.g. 'GET', 'POST', etc)
  • url{string|TrustedObject} – Absolute or relative URL of the resource that is being requested; or an object created by a call to $sce.trustAsResourceUrl(url).
  • params{Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
  • data{string|Object} – Data to be sent as the request message data.
  • headers{Object} – 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. Functions accept a config object as an argument.
  • eventHandlers - {Object} - Event listeners to be bound to the XMLHttpRequest object. To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
  • uploadEventHandlers - {Object} - Event listeners to be bound to the XMLHttpRequest upload object. To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.
  • xsrfHeaderName{string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName{string} – Name of cookie containing the XSRF token.
  • transformRequest{function(data, headersGetter)|Array.<function(data, headersGetter)>} – 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. See Overriding the Default Transformations
  • transformResponse{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} – transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default Transformations
  • paramSerializer - {string|function(Object<string,string>):string} - A function used to prepare the string representation of request parameters (specified as an object). If specified as string, it is interpreted as function registered with the $injector, which means you can create your own serializer by registering it as a service. The default serializer is the $httpParamSerializer; alternatively, you can use the $httpParamSerializerJQLike
  • cache{boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.
  • timeout{number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

    A numerical timeout or a promise returned from $timeout, will set the xhrStatus in the response to "timeout", and any other resolved promise will set it to "abort", following standard XMLHttpRequest behavior.

  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.

  • responseType - {string} - see XMLHttpRequest.responseType.



A Promise that will be resolved (request success) or rejected (request failure) with a response object.

The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.
  • statusText{string} – HTTP status text of the response.
  • xhrStatus{string} – Status of the XMLHttpRequest (complete, error, timeout or abort).

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. More information about the status might be available in the xhrStatus property.

Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code.




<div ng-controller="FetchController">
  <select ng-model="method" aria-label="Request method">
  <input type="text" ng-model="url" size="80" aria-label="URL" />
  <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  <button id="samplejsonpbtn"
    Sample JSONP
  <button id="invalidjsonpbtn"
    ng-click="updateModel('JSONP', '')">
      Invalid JSONP
  <pre>http status code: {{status}}</pre>
  <pre>http response data: {{data}}</pre>
angular.module('httpExample', [])
.config(['$sceDelegateProvider', function($sceDelegateProvider) {
  // We must whitelist the JSONP endpoint that we are using to show that we trust it
.controller('FetchController', ['$scope', '$http', '$templateCache',
  function($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}).
        then(function(response) {
          $scope.status = response.status;
          $ =;
        }, function(response) {
          $ = || 'Request failed';
          $scope.status = response.status;

    $scope.updateModel = function(method, url) {
      $scope.method = method;
      $scope.url = url;
Hello, $http!
  var status = element(by.binding('status'));
  var data = element(by.binding('data'));
  var fetchBtn = element('fetchbtn'));
  var sampleGetBtn = element('samplegetbtn'));
  var invalidJsonpBtn = element('invalidjsonpbtn'));

  it('should make an xhr GET request', function() {;;
    expect(data.getText()).toMatch(/Hello, \$http!/);

// Commented out due to flakes. See
// it('should make a JSONP request to', function() {
//   var sampleJsonpBtn = element('samplejsonpbtn'));
//   expect(status.getText()).toMatch('200');
//   expect(data.getText()).toMatch(/Super Hero!/);
// });

  it('should make JSONP request to invalid URL and invoke the error handler',
      function() {;;
    expect(data.getText()).toMatch('Request failed');