angulargoogle-cloud-functionscapacity

capacitor http plugin to avoid pre-flight request


I am trying to do post request to cloud function using capacitor http plugin to avoid triggering pre-flight request. But every time getting error Response body is not available to scripts (Reason: CORS Preflight Did Not Succeed)

Here is http.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http, HttpOptions } from '@capacitor-community/http';
import { from, Observable } from 'rxjs';

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

  constructor() { }

  doGet(url) {
    const options: HttpOptions = {
      url
    }
    return from(Http.get(options));
  }

  doPost(url): Observable<any> {
    const options: HttpOptions = {
      url,
      method: 'POST',
      headers: { 'content-type': 'application/json','Authorization': 'Bearer id_token' },
      data: { foo: 'bar', cool: true },
    };

    return from(Http.request(options));
  }
}

And home.page.ts

import { Component } from '@angular/core';
import { HttpService } from '../services/http.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  data = null;
  constructor(private httpService: HttpService) { }

  nativeCall() {
    this.httpService.doPost('https://xxxxx/cloude_function_name').subscribe((res: any) => {
      console.log(res);
      this.data = res.data.specials;
    });
  }

}

Any help will be appreciated.


Solution

  • After doing a lot of research I found out that we can not bypass CORS in web view even using capacitor-community/http plugin for ionic app. Reference (https://github.com/capacitor-community/http/issues/28#issuecomment-654932498).

    We can use capacitor-community/http plugin to bypass CORS in native app but not in web view.