API-call with Basic Authorization

Hey,

there have been some threads on this topic but I couldn’t find a solution.

My problem: I’ve an API (written in PHP) which seems to work. I can send a request and get the data. There is a basic authorization with username/password which works. I can get the data through browser or through postman (or paw which seems to be a nice tool too).

Not I try to call this api-endpoint through my app. The api gets called but doesn’t add the authorization-header no matter what I try. In the firefox dev tools I see that the request is missing the authorization-header. Can anyone enlighten me? Thank you.
My code:

  let headers = new Headers();
    headers.append("authorization", "basic aGM0YXBwOmHjddP5NjU=");
    headers.append("Content-Type","application/json");

    let options = new RequestOptions({ headers: headers });
    return  this.http.get(this.apiUrl, options)
            .do((res : Response ) => console.log(res.json())
            .map((res : Response ) => res.json())
            .catch(error => console.log(error)));
  }

Take a look to HttpClient. Http will be deprecated: https://angular.io/guide/http

Thanks, I was mixing up some things I guess, I was using HttpClient but just headers. I changed to HttpHeaders() but I have still the same problem. The API gets called, but is missing the Authorization-header.

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class RemoteServiceProvider {
  results : any;
  apiUrl : string = "https://www.example.com/api/user/id/1/format/json";

  constructor(public http: HttpClient) {
  }

  getAddress() {
    this.http.get(this.apiUrl, {
            headers: new HttpHeaders().set('Authorization', 'basic aGM0YXBwOmHjddP5NjU='),
          })
          .subscribe(data => {
            this.results = data;
          })
    return this.results;
    }
}
Accept	
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding	
gzip, deflate, br
Accept-Language	
de,en-US;q=0.7,en;q=0.3
Access-Control-Request-Headers	
authorization
Access-Control-Request-Method	
GET
Cache-Control	
no-cache
Connection	
keep-alive
Host	
www.example.com
Origin	
http://localhost:8100
Pragma	
no-cache
User-Agent	
Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/57.0

so this is from ionic serve ?

if so, you may need to setup the proxy for testing

Yes, it is from ionic-serve.

You mean add a service proxy like on https://ionicframework.com/docs/cli/configuring.html#using-a-proxy into ionic.config.json?

no from here

http://blog.ionicframework.com/handling-cors-issues-in-ionic/

Setting up the proxy urls
section.
if confusing i can help

Thanks, it works. Adding a proxy to ionic.json.config was the solution. The link you provided seems to be for an ionic 2.

Hey,

Spending some more time on this. When I now go on my device or on an emulator, there is no proxy needed anymore, right? There is written a lot on the web and I cannot find a solution. Building my app for iOS works, I can copy it through Xcode to my iPhone but every API-call fails. I just don’t get anything.

I removed the proxy-part from ionic.json.config and used the https-address of the api which works. ionic serve works with the proxy, so the calls and so on should work. I also programmed a log-function in my API and it doesn’t get called.

What is the solution here? Do I have to add something?

Thanks a lot!

Edit: The console says:
"{“headers”:{“normalizedNames”:{},“lazyUpdate”:null,“headers”:{}},“status”:0,“statusText”:“Unknown Error”,“url”:null,“ok”:false,“name”:“HttpErrorResponse”,“message”:“Http failure response for (unknown url): 0 Unknown Error”,“error”:{“isTrusted”:true}}"

I guess this must be the problem. But the url should be correct. Or at least not null.

hi Jonas3344,
I have the same problem as you describe here. Did you find a solution for it?
Txs Edgar

Hey,

no, not really. I didn’t have the time to get into it and as it just was a test I kind of gave up a little bit (or wanted to do it later). So I don’t have a solution for that at the moment. But there sure is. Or at least should be. :wink:

Hi Jonas3344

I have the same problem as you and eheydenr describe here. It’s only in iOS device, in Android work fine. Did you find a solution for it?

Hi,

Some month after but hoping that it helps.

For just call with a basic header try this. Very simple but it works.

import {HTTP} from '@ionic-native/http';
@Injectable()
export class YourProvider {

constructor(public http: HTTP) {}

const header = {
    'Authorization' : 'Bearer '+ token
 };

 this.http.get(this.url, {}, header)
    .then(data => {
         console.log(data);
    }).catch(error => {
        console.log(error);
    });
}
1 Like

thank u alex it’s working…