Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

CORS Issue Causing RestConnection Failed Error

Abierto
#3,572 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Necesita aclaración
Estado de actividad
Estancado
Stack tecnológico
angular, firebase, typescript

Línea de trabajo

Comienza con App.config.ts y FirebaseApiService, especialmente con getCountByQuery y su llamada a getCountFromServer, y luego reproduce la consulta con ionic serve. Compara la configuración de App Check, la configuración de Firebase y las versiones de las dependencias en package.json con los errores de red reportados. Se considera terminado cuando se haya identificado y documentado la causa, junto con una solución verificada para la consulta de Firestore.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

I'm developing an Angular application using AngularFire to interact with Firebase Firestore. When attempting to perform a specific query on Firestore, I'm encountering CORS errors and connection failures. I need help understanding why this is happening and how to fix it.

Error Messages

1.[Get & POST ERROR] ERROR

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 Error]
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 Policy Error]

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.[INTERNAL ASSERTION FAILED]
Error: FIRESTORE (10.12.4) INTERNAL ASSERTION FAILED: Unexpected state

5.[Appcheck failed]
[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.
Query Detail FROM 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",

STEP THAT I HAVE TRIED

Updating Angular & Firebase versions: No improvement in the CORS errors despite upgrading/downgrading versions.

Modifying CORS settings in Google Cloud Storage: No effect on Firestore requests.
{ "origin": ["*"], "method": ["GET", "POST", "PUT", "DELETE"], "responseHeader": ["Content-Type"], "maxAgeSeconds": 3600 } ]

Attempting SSR (Server-Side Rendering): Could not complete setup due to lack of documentation. (reverted back)

Reverting to previous stable versions: Errors persisted after rollback.

Using Firebase SDK directly without @angular/fire: Same errors, indicating @angular/fire wasn't the issue.

Registering an App Check debug token: Did not resolve the issue. (I have provided the debug token to the firebase console app check, but I am not sure where to use in app.config.ts)

Despite these steps, the CORS and connection issues remain unresolved.

These errors occur consistently, and none of the attempted solutions have resolved the issue.

Additional Information:
I've confirmed that the Firebase configuration (environment.firebase) is correct and matches the settings in the Firebase console. Firestore security rules have been checked and should allow the read operations I'm attempting. The application was working previously, and the issue started occurring after updating some dependencies, though reverting did not fix it. I'm running the application locally using ionic serve, which serves on http://localhost:8100 and production page. Question: Given these troubleshooting steps and the persistent CORS errors when making Firestore queries, what could be causing this issue, and how can I resolve it?

Lenguaje dominante
TypeScript
Estrellas
7.8k
Forks
2.2k
Merge medio
3 d 6 h
PR fusionados (30 d)
5

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de angular/angularfire

Todos los issues de angular/angularfire

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.