0

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.

patel887
  • 167
  • 1
  • 11
  • Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – The Fabio Apr 05 '22 at 22:30
  • because your angular app is not running on the same domain as your api you cannot avoid having to configure CORS in your Api, that's something all top market browsers implement. – The Fabio Apr 05 '22 at 22:32
  • So there is no way that I can bypass CORS with changing my request ? – patel887 Apr 06 '22 at 00:37
  • no... not when you are using a market standard browser. – The Fabio Apr 06 '22 at 00:56
  • Kindly post this as an answer so that the community would find this helpful. – Robert G Apr 06 '22 at 05:48

1 Answers1

1

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.

patel887
  • 167
  • 1
  • 11