【问题标题】:Angular PWA not caching server requestsAngular PWA 不缓存服务器请求
【发布时间】:2019-11-01 14:25:11
【问题描述】:

我创建了一个网站,它也可以作为 Angular 8 的 PWA 使用。我也将 Angular Universal 用于 SSR。它可以工作,也可以离线。问题是只有站点被缓存,而不是服务器请求。我在 ngsw 设置中添加了dataGroups。

这些是我的 ngsw-config.json

{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "dataGroups": [
    {
      "name": "exercises-requests",
      "urls": [
        "/api/provide-exercise"
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 100,
        "maxAge": "3d"
      }
    }
  ],
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}

这是我的 http 服务:

import { Injectable, isDevMode } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Input } from '../exercise/exercise.service';

export interface UserInfo {
  // ...
}
export interface ProvideExerciseBody {
  // ...
}
export interface ProvideExerciseResponse {
  // ...
}

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

@Injectable({
  providedIn: 'root',
})
export class HttpService {

  get
  serverDomain(): string {
    return isDevMode() ? 'https://unitn-statistica.herokuapp.com' : '';
  }

  constructor(private http: HttpClient) { }

  provideExercise(body: ProvideExerciseBody): Observable<ProvideExerciseResponse> {
    return this.http.post<ProvideExerciseResponse>(this.serverDomain + '/api/provide-exercise', body, httpOptions)
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(err: HttpErrorResponse) {
    const error = err.error;
    if (error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.message);
      console.error(error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${err.status}, ` +
        `body was: ${error}`);
      console.log(error);
    }
    // return an observable with a user-facing error message
    return throwError(error.message);
  }

}

而且我确信服务器调用是正确的

app.post('/api/provide-exercise', (req, res) => { ... }

我不明白为什么我对服务器的发帖请求没有被缓存。

【问题讨论】:

    标签: angular typescript angular-universal angular-service-worker angular-pwa


    【解决方案1】:

    我认为您面临的问题是 Angular 的 Service Worker 不会缓存 POST 请求,无论它是如何配置的。原因是 POST 请求通常意味着改变服务器上的资源。因此缓存这个请求并没有真正的用处。

    这是排除任何变异请求的代码的相关部分:https://github.com/angular/angular/blob/master/packages/service-worker/worker/src/data.ts#L283

    也许您可以控制服务器并且您发出的请求不会改变任何内容。那么使用 GET 请求可能是一个很好的解决方案。

    但是,如果请求确实改变了某些内容,但您仍想缓存响应,那么使用 localStorage 或 IndexedDB 等其他缓存策略可能是一种解决方案。

    【讨论】:

    • 我觉得你很紧张。问题是这样的:网站要求您输入(固定为所有人)用户名和密码,以及日期。服务器检查用户密码并返回该日期的行使。还传递保留的数据,如用户和密码,我必须使用 POST。但这会阻止我缓存练习,因此 pwa 变得无用,因为每次调用练习都会失败。我如何确保使用本地存储,数据将持续存在?
    • 您不能 100% 确定数据会被持久化。与任何其他用户数据一样,用户可能会决定在任何时间点将其删除。但这也适用于服务工作者的缓存。但我猜下载/安装 PWA 的人不想删除数据。
    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    相关资源
    最近更新 更多