itsource

Angular 2에서 IE11 캐싱 GET 호출 방지

mycopycode 2023. 8. 20. 10:48
반응형

Angular 2에서 IE11 캐싱 GET 호출 방지

GET 호출에 대한 목록을 반환하는 Rest Endpoint가 있습니다.또한 새 항목을 추가할 POST 끝점과 제거할 DELETE가 있습니다.이것은 Firefox와 Chrome에서 작동하고 POST와 DELETE는 IE11에서 작동합니다.그러나 IE11의 GET는 페이지의 초기 로드에서만 작동합니다.새로 고침은 캐시된 데이터를 반환합니다.나는 Angular 1에서 이 행동에 대한 게시물을 보았지만 Angular 2(릴리스 후보 1)에 대한 게시물은 없었습니다.

Angular 2 이상의 경우 재정의하여 캐시 없음 헤더를 추가하는 가장 쉬운 방법RequestOptions:

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

모듈:

@NgModule({
    ...
    providers: [
        ...
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ]
})

오늘 저도 이런 문제가 있었습니다.내 프로젝트에서, 나는 사용합니다.httpclient그렇지 않은BaseRequestOptions우리는 사용해야 합니다.Http_Interceptor해결하기 위해!

import { HttpHandler,
    HttpProgressEvent,
    HttpInterceptor,
    HttpSentEvent,
    HttpHeaderResponse,
    HttpUserEvent,
    HttpRequest,
    HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

export class CustomHttpInterceptorService implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler):
      Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
      const nextReq = req.clone({
        headers: req.headers.set('Cache-Control', 'no-cache')
          .set('Pragma', 'no-cache')
          .set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')
          .set('If-Modified-Since', '0')
      });

      return next.handle(nextReq);
  }
}

모듈 제공

@NgModule({
    ...
    providers: [
        ...
        { provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true }
    ]
})

$http에 대한 스택 오버플로 응답 Angular IE 캐싱 문제를 전달하려면 각 'GET' 요청에 'Pragma', 'no-cache', 'If-Modified-Since' 헤더를 추가해야 합니다.

절편 시나리오는 각도 2에서 더 이상 지원되지 않습니다.따라서 여기에 설명된 대로 http를 확장해야 합니다. http 가로채기는 angular2에 해당하는 것이 무엇입니까?

Angular 4.3은 이제 인터셉트를 지원하는 HttpClient 서비스를 포함합니다.

편집: 아래 설명을 참조하십시오. 이것은 필요하지 않습니다(대부분의 경우).

위의 Jimmy Ho의 답변을 확장하면, 저는 API 호출의 캐싱을 방지하고 캐시의 혜택을 받는 다른 정적 콘텐츠를 방지하고 싶습니다.제 API 호출은 모두 "/api/"가 포함된 URL에 대한 것이므로, 요청된 URL에 "/api/"가 포함된 경우에만 캐시 헤더를 추가하는 검사로 Jimmy Ho의 코드를 수정했습니다.

import { HttpHandler,
    HttpProgressEvent,
    HttpInterceptor,
    HttpSentEvent,
    HttpHeaderResponse,
    HttpUserEvent,
    HttpRequest,
    HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

export class CustomHttpInterceptorService implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
    // Only turn off caching for API calls to the server.
    if (req.url.indexOf('/api/') >= 0) {
        const nextReq = req.clone({
            headers: req.headers.set('Cache-Control', 'no-cache')
                .set('Pragma', 'no-cache')
                .set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')
                .set('If-Modified-Since', '0')
        });

        return next.handle(nextReq);
    } else {
        // Pass the request through unchanged.
        return next.handle(req);
    }
}

}

위의 답변과 같이 http 요청 가로채기를 사용하여 요청에 대한 헤더를 수정하거나 새 헤더를 설정할 수 있습니다.다음은 후기 각 버전(Angular 4+)에 대한 http 요청 가로채기의 헤더를 설정하는 훨씬 간단한 방법입니다.이 접근 방식은 특정 요청 헤더만 설정하거나 업데이트합니다.이는 권한 부여 헤더와 같은 일부 중요한 헤더를 제거하거나 재정의하지 않도록 하기 위한 것입니다.

// cache-interceptor.service.ts
import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
} from '@angular/common/http';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const httpRequest = req.clone({
      headers: req.headers
        .set('Cache-Control', 'no-cache')
        .set('Pragma', 'no-cache')
        .set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')
    })

    return next.handle(httpRequest)
  }
}

// app.module.ts

  import { HTTP_INTERCEPTORS } from '@angular/common/http'
  import { CacheInterceptor } from './cache-interceptor.service';

  // on providers
  providers: [{ provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }]

메타 HTML 태그로 브라우저 캐싱 사용 안 함:-

<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0">
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">

조금 늦었지만, 저도 같은 문제에 부딪혔습니다.Angular 4.X의 경우 IE에 의한 캐싱을 방지하기 위해 끝에 난수를 추가하는 사용자 정의 Http 클래스를 작성했습니다.이는 2진수에 의한 2번째 링크를 기반으로 합니다(http interceptor in angular2는 무엇입니까?).경고: 100% 버그가 없을 것으로 보장되지 않습니다.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response, XHRBackend, RequestOptions, RequestOptionsArgs, 
URLSearchParams } from '@angular/http';

@Injectable()
export class NoCacheHttp extends Http {
    constructor(backend: XHRBackend, options: RequestOptions) {
        super(backend, options);
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        //make options object if none.
        if (!options) {
            options = { params: new URLSearchParams() };
        }
        //for each possible params type, append a random number to query to force no browser caching.
        //if string
        if (typeof options.params === 'string') {
            let params = new URLSearchParams(options.params);
            params.set("k", new Date().getTime().toString());
            options.params = params;

        //if URLSearchParams
        } else if (options.params instanceof URLSearchParams) {
            let params = <URLSearchParams>options.params;
            params.set("k", new Date().getTime().toString());

        //if plain object.
        } else {
            let params = options.params;
            params["k"] = new Date().getTime().toString();
        }
        return super.get(url, options);
    }
}

언급URL : https://stackoverflow.com/questions/37755782/prevent-ie11-caching-get-call-in-angular-2

반응형