瀏覽器兼容性之IE瀏覽器http請求緩存問題

問題描述

在 IE 瀏覽器上使用 GET 請求時,只有第一次請求會到服務端,後續請求會直接從瀏覽器緩存中讀取。執行完增刪改操做後,沒法獲取最新數據。
(注:開發環境Angular8.1.0ng-zorro-antd:~8.0.2,前端容器nginx:1.10.1。)前端

解決方案

此處提供兩種簡潔的解決途徑,具體以下。nginx

一、經過http攔截器設置請求頭

新增InterceptorService.ts文件,經過HttpInterceptor接口中的intercept()方法類,對請求進行攔截。使用setHeaders方法統一設置請求頭的Cache-ControlPragma屬性值爲no-cache,代碼實現以下:api

export class InterceptorService implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
        const newReq = req.clone({  
            setHeaders: {  
                'Cache-Control': 'no-cache',  
                'Pragma': 'no-cache'
             }  
        });  
        return next.handle(newReq).pipe(  
            catchError((err: HttpErrorResponse) => return throwError(event))  
        );  
    }
}

二、更改nginx配置

經過Nginxngx_http_headers_module模塊對Cache-Control進行配置。在接口轉發配置中添加add_header Cache-Control no-store。具體配置以下:瀏覽器

location /api {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    add_header Cache-Control no-store;
    proxy_read_timeout 360s;
    proxy_send_timeout 360s;
    if ( -f /data/ready ) {
        proxy_pass http://127.0.0.1:8333;
    }
    if ( !-f /data/ready ) {
        proxy_pass http://127.0.0.1:1337;
    }
}

Cache-Control常見取值及其釋義:
no-cache: 數據內容不能被緩存, 每次請求都從新訪問服務器, 如有max-age, 則緩存期間不訪問服務器。
no-store: 不只不能緩存, 連暫存也不能夠(即: 臨時文件夾中不能暫存該資源)。
max-age: 相對過時時間, 即以秒爲單位的緩存時間。
…………緩存

總結

此外,還能夠經過給 GET 請求增長隨機參數等方案解決該問題。服務器

相關文章
相關標籤/搜索