所有从IE发送的ajax调用都被Angular缓存了,我对所有后续调用都得到了一个304响应。虽然请求是一样的,但在我的情况下,响应是不一样的。我想禁用这个缓存。我尝试将缓存属性添加到$http。得到了,但还是没有用。如何解决这个问题?


当前回答

我得到它解决附加datetime作为一个随机数:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});

其他回答

你可以添加一个拦截器。

myModule.config(['$httpProvider', function($httpProvider) {
 $httpProvider.interceptors.push('noCacheInterceptor');
}]).factory('noCacheInterceptor', function () {
            return {
                request: function (config) {
                    console.log(config.method);
                    console.log(config.url);
                    if(config.method=='GET'){
                        var separator = config.url.indexOf('?') === -1 ? '?' : '&';
                        config.url = config.url+separator+'noCache=' + new Date().getTime();
                    }
                    console.log(config.method);
                    console.log(config.url);
                    return config;
               }
           };
    });

您应该在验证后删除console.log行。

只有这一行对我有帮助(Angular 1.4.8):

$httpProvider.defaults.headers.common['Pragma'] = 'no-cache';

UPD:问题是IE11进行了主动缓存。当我在研究Fiddler时,我注意到在F12模式下请求发送“Pragma=no-cache”,每次访问页面时都请求endpoint。但是在正常模式下,当我第一次访问页面时,端点只被请求了一次。

我得到它解决附加datetime作为一个随机数:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});

为了避免缓存,一种方法是为相同的资源或数据提供不同的URL。为了生成不同的URL,您可以在URL的末尾添加一个随机查询字符串。该技术适用于JQuery、Angular或其他类型的ajax请求。

myURL = myURL +"?random="+new Date().getTime();

我所做的保证是这样的:

myModule.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.common) {
        $httpProvider.defaults.headers.common = {};
    }
    $httpProvider.defaults.headers.common["Cache-Control"] = "no-cache";
    $httpProvider.defaults.headers.common.Pragma = "no-cache";
    $httpProvider.defaults.headers.common["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT";
}]);

为了保证所有方法的正确使用,我不得不合并上述两个解决方案,但你可以用get或其他方法替换common,即put, post, delete,以使其适用于不同的情况。