CORS Issue when sending request from ionic to firebase cloud function

I am trying to send a HTTP request to a firebase cloud function in my Ionic Angular app, but am facing a CORS issue.

Here is the function I am trying to execute:

import { HttpClient } from '@angular/common/http';
private http: HttpClient

like(post) {
this.http.post('cloudFunctionUrl', JSON.stringify(body), {
      responseType: 'text'
    }).subscribe((data) => {
      console.log(data);
    }, (error) => {
      console.log(error);
    });
}

To get over the CORS issue, I installed the Allow CORS: Access-Control-Allow-Origin chrome plugin. Below is a list of the whitelisted domains:

The like function above is executed on localhost:8100/profile

I’m experiencing two issueS:

  1. I navigate to localhost:8100/profile no problem, but when I execute like , I get this error message:

Access to XMLHttpRequest at ‘cloudFunctionUrl’ from origin ‘http://localhost:8100’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

  1. If I go to the firebase console, & I have the CORS plugin turned on, it says “There was an error loading your projects”

Can someone please tell me how I can resolve this?

I also tried to add the below headers to the request, but the error is still appearing:

let headers = new HttpHeaders({
      'Access-Control-Allow-Origin': '*'
    });
    this.http.post('cloudFunctionUrl', JSON.stringify(body), {
      headers: headers,
      responseType: 'text'
    }

Insted of httpclient use this http, but it will only work in real device, not in browser

and put following code inside your platform ready

this.http.setServerTrustMode('pinned', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

and use following for post

this.http.post('cloudFunctionUrl', JSON.stringify(body), {}).then((response)=>{
   var data = JSON.parse(response);
console.log(data);
})

it will only work in real device

1 Like

Thanks for the quick response.

So I’ve updated my post to match what you were mentioning above:

like(post) {

    let body = {

      postId: post.id,

      userId: firebase.auth().currentUser.uid,

      action: post.data().likes && post.data().likes[firebase.auth().currentUser.uid] === true ? 'unlike' : 'like'

    }

    this.http.post('cloudFunctionUrl', JSON.stringify(body), {}).then((response) => {

      var data = JSON.parse(response.toString());

      console.log(data);

    });

  }

I ran this in a device using ionic cordova run android and here is the error message now:

Uncaught (in promise): Error: advanced-http: “data” option is configured to support only following data types: Object
Error: advanced-http: “data” option is configured to support only following data types: Object

Also, where should I put setServerTrustMode()?

remove JSON.stringify() and try

1 Like