AngularJS HTTP GET request returns cached data

In my AngularJS application, I am sending an HTTP GET request as shown below.

MyService.HttpReq("testUrl", "GET", null);

HttpReq The method is defined in the service and implemented below:

this.HttpReq = function(URL, method, payload)
{
    $http({
        url: URL,
        method: method,
        cache: false,
        data: postData,
        headers: {
            'Content-Type': 'application/json',
        }
    }).success(function(response)
    {
        console.log("Success: "+JSON.stringify(response));

    }).error(function(data, status)
    {
       console.error("Error");

    });
}

First of all, is this the correct way to send an HTTP request in AngularJS?
The problem I am facing is that sometimes I get cached data as a response, and the HTTP request does not get to the server. what could be the problem?

UPDATE

In accordance with the comment and the answer, I updated my HTTP request code as below, but still getting the same problem.

this.HttpReq = function(URL, method, payload)
{
    $http({
        url: URL, 
        method: method, 
        cache: false,
        data: payload,
        headers: {
            'Content-Type': 'application/json',
            'Cache-Control' : 'no-cache'
        }
    }).
    then(
        function(response) 
        {
            var data = response.data;
            console.log("Success: "+JSON.stringify(data));
        }, 
        function(response) 
        {
            var data = response.data || "Request failed";
            var status = response.status;
            console.error("Error: "+JSON.stringify(data));
        }
    );
}
+4
source share
2 answers

Just add the cache: false attribute to the configuration object.

https://docs.angularjs.org/api/ng/service/$http#caching

: "Cache-Control": "no-cache"

+1

IE ajax, . , , - . , api ,

 MyService.HttpReq("testUrl?ts=" + Date.now(), "GET", null);
+2

All Articles