CORS 问题导致 AngularFire 应用程序出现 RestConnection 失败错误

问题描述 投票:0回答:1

我正在开发一个 Angular 应用程序,使用 AngularFire 与 Firebase Firestore 进行交互。尝试在 Firestore 上执行特定查询时,我遇到 CORS 错误和连接失败。我需要帮助了解为什么会发生这种情况以及如何解决它。

错误消息

1.[获取并发布错误]错误

zone.js:2675 
 GET https://firestore.googleapis.com/google.firestore.v1.Firestore/Write... (Bad Request)

POST https://firestore.googleapis.com/v1/projects/prettyofsystem/databases/(default)/documents/shop/tJOmcKufDrBEfQwpyoxM:runAggregationQuery net::ERR_FAILED

2.[RestConnection RPC 错误]

chunk-2OX4UKGE.js?v=e7a89523:77 [2024-10-24T15:14:33.417Z]  
@firebase/firestore: Firestore (10.12.4): RestConnection RPC 'RunAggregationQuery' 0x1a504b0b failed with error:  {"code":"unavailable","name":"FirebaseError"} url:  https://firestore.googleapis.com/v1/projects/prettyofsystem/databases/(default)/documents/shop/tJOmcKufDrBEfQwpyoxM:runAggregationQuery request: {"structuredAggregationQuery":{"aggregations":[{"alias":"aggregate_0","count":{}}],"structuredQuery":{"from":[{"collectionId":"consult"}],"where":{"compositeFilter":{"op":"AND","filters":[{"fieldFilter":{"field":{"fieldPath":"client.id"},"op":"EQUAL","value":{"stringValue":"de1kRJEkF3K3EJ2RuZdU"}}},{"fieldFilter":{"field":{"fieldPath":"status.type"},"op":"EQUAL","value":{"stringValue":"Completed"}}}]}}}}}

3.【CORS策略错误】

Access to XMLHttpRequest at 'https://firestore.googleapis.com/v1/projects/prettyofsystem/databases/(default)/documents/shop/tJOmcKufDrBEfQwpyoxM:runAggregationQuery' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

4.[内部断言失败]

Error: FIRESTORE (10.12.4) INTERNAL ASSERTION FAILED: Unexpected state

5.[应用检查失败]

[2024-10-24T16:06:37.735Z]  @firebase/firestore: Firestore (10.12.4): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unknown]: Fetching auth token failed: AppCheck: Fetch server returned an HTTP error status. HTTP status: 403. (appCheck/fetch-status-error).
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

从 FirebaseAPIService [providedIn Root] 查询详细信息

import { setDoc, getCountFromServer } from '@angular/fire/firestore';
private firestore = inject(Firestore);
private docRef = (segment: string, documentId: string): DocumentReference<DocumentData> => {
    return doc(this.firestore, getPath(segment, documentId));
  };  

private collection = (path: string): CollectionReference<DocumentData> => {
    return collection(this.firestore, path);
  };

private query = (path: string, ...queryConstraints: QueryConstraint[]): FirestoreQuery<DocumentData> => {
return query(this.collection(path), ...queryConstraints);
  };

public async setDocument<T extends { id?: string }>(path: string, dto: T): Promise<string | null> {
    try {
      const docId = dto?.id && dto.id.length > 0 ? dto.id :  this._newIdSvc.getNewDocumentId();
      const newDocument = this.docRef(path, docId);
      const document = { ...dto, id: docId };
      await setDoc(newDocument, document);
      return docId;
    } catch (error) {
      console.error(error);
      return null;
    }
  }

public getCountByQuery(path: string, ...queries: QueryConstraint[]): Observable<number> {
    return defer(() => from(getCountFromServer(this.query(path, ...queries)))).pipe(
      startTraceByQuery(path, ...[...queries]),
      map(snapshots => snapshots.data().count),
      map(doc => {
        if (this.isDebugMode()) {
          console.log(`getCount: ${path} ${queryDescription(...[...queries])} `, doc);
        }
        return doc;
      }),
      catchError(error => {
        console.error(`getCount: ${path} ${queryDescription(...[...queries])} `, error);
        return of(0);
      })
    );
  }

App.config.ts

const config: ApplicationConfig = {
  providers: [
    // Ionic
    provideSvgIcons(),
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    provideIonicAngular({ swipeBackEnabled: false, mode: 'md', navAnimation: routingAnimation }),
    importProvidersFrom(IonicModule.forRoot({ swipeBackEnabled: false, mode: 'md',
navAnimation:routingAnimation })),
    importProvidersFrom(IonicStorageModule.forRoot()),

    // Angular
    provideHttpClient(withFetch()),
    provideAnimations(),
    ...

    // Firebase initialization
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideRemoteConfig(() => getRemoteConfig(getApp())),
    provideAnalytics(() => getAnalytics(getApp())),
    provideFirestore(() => getFirestore(getApp())),
    provideStorage(() => getStorage(getApp())),
    provideFunctions(() => getFunctions(getApp())),
    provideMessaging(() => getMessaging(getApp())),
    provideDatabase(() => getDatabase(getApp())),
    provideAuth(() => {
      if (Capacitor.isNativePlatform()) {
        console.log('Initializing auth with indexedDBLocalPersistence');
        return initializeAuth(getApp(), {
          persistence: indexedDBLocalPersistence,
        });
      }
      return getAuth();
    }),
    provideAppCheck(() => initializeAppCheck(getApp(), {
      provider: new ReCaptchaEnterpriseProvider(environment.WebSiteKey),
      isTokenAutoRefreshEnabled: true,
    })),

    // Root Services
    UserTrackingService,
    ScreenTrackingService,
    LanguageService,
    FirebaseApiService,
    PushNotificationService,
    AuthService,
    PushNotificationService,
    PrimeNGConfigService,
    MessageService,
    ConfirmationService,
    ToastMessageService,
  ],
};

package.json

    "@angular/animations": "^18.2.1",
    "@angular/cdk": "18.2.1",
    "@angular/common": "^18.2.1",
    "@angular/core": "18.2.1",
    "@angular/fire": "^18.0.1",
    "@angular/forms": "^18.2.1",
    "@angular/localize": "^18.2.1",
    "@angular/material": "^18.2.1",
    "@angular/platform-browser": "^18.2.1",
    "@angular/platform-browser-dynamic": "^18.2.1",
    "@angular/router": "^18.2.1",
    "@angular/service-worker": "^18.2.1",
    "firebase": "10.12.4",

我尝试过的步骤

  1. 更新 Angular 和 Firebase 版本: 尽管升级/降级版本,CORS 错误没有改善。

  2. 修改 Google Cloud Storage 中的 CORS 设置: 对 Firestore 请求没有影响。
    {“origin”:[“*”],“method”:[“GET”,“POST”,“PUT”,“DELETE”],“responseHeader”:[“Content-Type”],“maxAgeSeconds”:3600 }]

  3. 尝试SSR(服务器端渲染):由于缺乏文档而无法完成设置。 (恢复原状)

  4. 恢复到以前的稳定版本:回滚后错误仍然存在。

  5. 直接使用Firebase SDK而不使用

    @angular/fire
    同样的错误,表明
    @angular/fire
    不是问题所在。

  6. 注册 App Check 调试令牌: 未解决问题。 (我已向 firebase 控制台应用程序检查提供了调试令牌,但我不确定在 app.config.ts 中使用何处)

尽管采取了这些步骤,CORS 和连接问题仍未解决。

这些错误持续发生,并且尝试的解决方案都没有解决该问题。

附加信息:

我已确认 Firebase 配置 (environment.firebase) 正确并且与 Firebase 控制台中的设置匹配。 Firestore 安全规则已经过检查,应该允许我尝试的读取操作。 该应用程序之前运行正常,更新一些依赖项后开始出现问题,但恢复并没有解决问题。 我使用 ionicserve 在本地运行应用程序,该服务在 http://localhost:8100 和生产页面上提供服务。 问题:考虑到这些故障排除步骤以及进行 Firestore 查询时持续存在的 CORS 错误,可能会导致此问题的原因是什么,以及如何解决它?

angular firebase ionic-framework cors angularfire2
1个回答
0
投票

面临相同的 CORS 问题,但仅限于某些设备的生产环境。尝试解决此问题并寻找解决方案,但未能解决问题。看不到这个问题的任何解决方案

© www.soinside.com 2019 - 2024. All rights reserved.