Capacitor Angular 8 all requests fail with HttpHeaders

Every API request I try to make with HTTP headers fails with this error:

Failed to load resource: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin.

However the request works when sending an empty as the header. How can I get around this issue?
Here is the code:

const httpOptions = {
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
        'Authorization' : 'Bearer ' + this.token,
        'Content-Type': 'application/json'
      })
    };

    return this.http.get(endpoint, httpOptions);

Here is my ionic info:

ionic info

Ionic:

   Ionic CLI                     : 6.9.2 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.0.7
   @angular-devkit/build-angular : 0.803.26
   @angular-devkit/schematics    : 8.3.26
   @angular/cli                  : 8.3.26
   @ionic/angular-toolkit        : 2.2.0

Capacitor:

   Capacitor CLI   : 2.0.1
   @capacitor/core : 2.0.1

Utility:

   cordova-res (update available: 0.14.0) : 0.13.0
   native-run (update available: 1.0.0)   : 0.3.0

System:

   NodeJS : v10.15.1 (/usr/local/bin/node)
   npm    : 6.14.5
   OS     : macOS Catalina

Take a look at the docs.

The browser headers are going to be ignored. These are things that need to be setup on the server side.

1 Like

This is setup server side, in fact the exact code worked fine using ionic 3 with the standard headers in place of HttpHeaders.

import { Http, Headers, RequestOptions, URLSearchParams } from ‘@angular/http’;

let endpoint = this.getBaseURL() + object;
let headers = new Headers();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + this.token);
headers.append('x-csrf-token', '_csrf');


this.http.get(endpoint, {headers: headers})
  .timeout(200000)
  .map(response => { 
    if(response) { 
      this.data = response.json();
      this.storage.set(object, this.data);
      return this.data;
    }       
  })
  .catch(err =>  { 
  });