AngularJS HTTP GET请求返回缓存数据

时间:2016-06-15 13:17:28

标签: angularjs http-get

在我的AngularJS应用程序中,我发送HTTP GET请求,如下所示。

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

HttpReq方法在服务中定义,并按如下方式实现:

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");

    });
}

首先,这是在AngularJS中发送HTTP请求的正确方法吗? 我面临的问题是,有时我将缓存数据作为响应而HTTP请求没有到达服务器。可能是什么问题?

更新

根据评论和回答,我已更新了我的HTTP请求代码,如下所示,但仍然遇到同样的问题。

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));
        }
    );
}

2 个答案:

答案 0 :(得分:2)

即使我们将缓存控制标头添加到响应中,IE浏览器也会捕获ajax get请求。我发现解决问题的唯一方法是在请求中添加一些随机参数。即使你发送额外的参数,请确保api没有问题

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

答案 1 :(得分:1)

只需将 cache:false 属性添加到配置对象。

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

您还可以添加标题:' Cache-Control' :' no-cache'