Problema de caché de IE angular para http http


Todas las llamadas ajax que se envían desde el IE se almacenan en caché por Angular y obtengo un 304 response para todas las llamadas posteriores . Aunque la solicitud es la misma, la respuesta no va a ser la misma en mi caso. Quiero desactivar esta caché. He intentado añadir el cache attribute a http http.pero aún así no ayudó. Cómo se puede resolver este problema?

Author: Rahul, 2013-04-19

17 answers

En lugar de deshabilitar el almacenamiento en caché para cada solicitud GET, lo deshabilito globalmente en el htt httpProvider:

myModule.config(['$httpProvider', function($httpProvider) {
    //initialize get if not there
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};    
    }    

    // Answer edited to include suggestions from comments
    // because previous version of code introduced browser-related errors

    //disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    // extra
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
 425
Author: cnmuc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-05 00:30:46

Puede agregar una querystring única (creo que esto es lo que hace jQuery con la opción cache: false) a la solicitud.

$http({
    url: '...',
    params: { 'foobar': new Date().getTime() }
})

Una solución quizás mejor es si tiene acceso al servidor, entonces puede asegurarse de que los encabezados necesarios estén configurados para evitar el almacenamiento en caché. Si estás usando ASP.NET MVC esta respuesta podría ayudar.

 68
Author: Martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:11

Puede agregar un interceptor .

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

Debe eliminar la consola.registre las líneas después de la verificación.

 28
Author: dillip pattnaik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-27 17:39:03

Simplemente agregué tres meta etiquetas en index.html en el proyecto angular, y el problema de caché se resolvió en IE.

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
 14
Author: rtato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-06 20:12:13

Para Angular 2 y posteriores , la forma más fácil de agregar encabezados mencionados es anular RequestOptions clase utilizada por Http servicio:

import { Injectable } from '@angular/core';
import { BaseRequestOptions, Headers } from '@angular/http';

@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
    headers = new Headers({
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
    });
}

Y referenciarlo en su módulo:

@NgModule({
    ...
    providers: [
        ...
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ]
})
 12
Author: Vitaliy Ulantikov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-15 07:20:41

El garantizado que tenía trabajando era algo en estas líneas:

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

Tuve que fusionar 2 de las soluciones anteriores con el fin de garantizar el uso correcto para todos los métodos, pero se puede reemplazar common con get u otro método es decir.put, post, delete para hacer que esto funcione para diferentes casos.

 9
Author: marksyzm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-17 09:35:02

Esta única línea me ayudó (Angular 1.4.8):

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

UPD: El problema es que IE11 hace almacenamiento en caché agresivo. Cuando estaba buscando en Fiddler me di cuenta de que en el modo F12 las solicitudes están enviando "Pragma=no-cache" y endpoint se solicita cada vez que visito una página. Pero en el modo normal endpoint se solicitó solo una vez en la primera vez que visité la página.

 7
Author: yamaxim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-03 12:00:05

Lo resuelvo añadiendo datetime como un número aleatorio:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});
 6
Author: khichar.anil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-25 10:46:50

Para evitar el almacenamiento en caché, una opción es dar URL diferentes para el mismo recurso o datos. Para generar URL diferentes, puede agregar una cadena de consulta aleatoria al final de la URL. Esta técnica funciona para jQuery, Angular u otro tipo de solicitudes ajax.

myURL = myURL +"?random="+new Date().getTime();
 6
Author: Razan Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-22 05:37:41

Solución anterior funcionará (hacer que la url única mediante la adición de la querystring un nuevo param) pero prefiero la solución proponer [aquí]: Mejor manera de Evitar IE Caché en AngularJS?, que manejan esto a nivel de servidor, ya que no es específico de IE. Es decir, si ese recurso no debe almacenarse en caché, hágalo en el servidor (esto no tiene nada que ver con el navegador utilizado; es intrisic para el recurso).

Por ejemplo en java con JAX-RS hacerlo programáticamente para JAX-RS v1 o declativly para JAX-RS v2.

Estoy seguro de que cualquiera descubrirá cómo hacerlo

 4
Author: rguitter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:34

He encontrado una mejor solución: Mejor Manera de Prevenir IE Cache en AngularJS?

Para los perezosos aquí hay una solución:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public ActionResult Get()
{
    // return your response
}
 1
Author: Vladislav Kurkotov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:47

Esto es un poco viejo pero: Soluciones como es obsoleto. Deje que el servidor maneje la caché o no (en la respuesta). La única manera de garantizar que no haya almacenamiento en caché (pensando en nuevas versiones en producción) es cambiar el archivo js o css con un número de versión. Hago esto con webpack.

 1
Author: Jens Alenius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-16 17:39:29

También puede intentar en su servce establecer encabezados como por ejemplo:

...
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";
...
 @Injectable()
export class MyService {

    private headers: HttpHeaders;


    constructor(private http: HttpClient..) 
    {


        this.headers = new HttpHeaders()
                    .append("Content-Type", "application/json")
                    .append("Accept", "application/json")
                    .append("LanguageCulture", this.headersLanguage)
                    .append("Cache-Control", "no-cache")
                    .append("Pragma", "no-cache")                   
    }
}
....
 1
Author: No Name,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-01 10:30:14

Este problema se debe al problema de caché de IE como ha dicho, puede probarlo en el modo de depuración de IE pulsando f12 (esto funcionará bien en el modo de depuración).IE no tomará los datos del servidor cada vez que la página llame, tomará los datos de la caché. Para desactivar esto, realice una de las siguientes acciones:

  1. agregue lo siguiente con su url de solicitud de servicio http

//Antes (expedido uno)

Esto.HTTPService.obtener (esto.Servicio + "/eAMobileService.svc / ValidateEngagmentName / " + engagementName , {})

//After (working fine)

Esto.HTTPService.obtener (esto.serviceUrl + " /eAMobileService.svc / ValidateEngagmentName / " + engagementName+"?DateTime= " + new Date().getTime ()+", {cache: false })

  1. desactivar la caché para todo el Módulo: -

$httpProvider.predeterminado.cabecera.common ['Pragma'] = 'sin caché';

 0
Author: Nijas_kp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 14:37:03
meta http-equiv="Cache-Control" content="no-cache"

Acabo de añadir esto para Ver y comenzó a trabajar en IE. Confirmado para trabajar en Angular 2.

 0
Author: Bharat Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-18 04:35:59

Siempre use un enfoque simple agregar marca de tiempo con cada solicitud no hay necesidad de borrar la caché

    let c=new Date().getTime();
    $http.get('url?d='+c)
 0
Author: Vaimeo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-27 08:33:39

Prueba esto, funcionó para mí en un caso similar:-

$http.get("your api url", {
headers: {
    'If-Modified-Since': '0',
    "Pragma": "no-cache",
    "Expires": -1,
    "Cache-Control": "no-cache, no-store, must-revalidate"
 }
})
 -1
Author: Mayank Parnami,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 11:32:32