Skip to main content

Caching HTTP responses

The $http service supports caching responses to HTTP requests. If same request is executed several times during a time period, $http can return a cached response instead of sending a new request to the server.

Caching requirements

For caching to work, the following requirements should be met:

  1. Before the HTTP request is executed, there is a call to $http.config with the cacheTimeToLiveInSeconds property set.
  2. $http.query is called with the cachingRequired property set to true.
  3. The request is successful, meaning that it has a 2XX status code. Responses to requests with an error are never cached.
  4. Repeated requests have the same method, url, headers, query, body, form, and dataType.
tip

If all of these requirements are met, the response to the first request will be cached. Subsequent identical requests within cacheTimeToLiveInSeconds will return the response from the cache.

How to use

The following example illustrates that the requests’ body and form are compared against each other structurally rather than literally. Here the response to the first request will be received from the server, and the second one will be taken from the cache.

init:
$http.config({
cacheTimeToLiveInSeconds: 10
});

theme: /

state: 1
q!: 1
script:
var body = {
key1: "value1",
key2: "value2",
foo: { foo: "bar", baz: "qux" },
c: null,
b: [3, 1, 2]
};

$http.query("https://httpbin.org/anything", {
method: "POST",
body: body,
cachingRequired: true
});

state: 2
q!: 2
script:
var body = {
b: [3, 1, 2],
key2: "value2",
key1: "value1",
foo: {
baz: "qux",
f: function () {}, // The function gets neither serialized nor sent in the request.
foo: "bar"
},
c: null
};

$http.query("https://httpbin.org/anything", {
method: "POST",
body: body,
cachingRequired: true
});