-1

I need to fetch data from an endpoint that require authentication (login). Once logged in json object is shows up. I am using HttpClient module of angular to get data like this.

 return this.http.get('https://jsonplaceholder.typicode.com/users');

If I do this on other apis (that doesn't require (login) works fine. But If I change serviceUrl to endpoint that require login. It gives me error Http failure response for (unknown url): 0 Unknown Error

May be I can do like this?

let headers = new HttpHeaders({'Content-Type': 'application/json'});
return this.http.get(this.serviceUrl, {headers: headers});
Umair Jameel
  • 1,573
  • 3
  • 29
  • 54
  • 1
    `If I change serviceUrl to endpoint that require login. It gives me error`, I guess you need to provide some credentials to api then, token maybe? Hard to say anything else when we don't know more :) – AT82 Feb 01 '18 at 19:23
  • 1
    If it requires login, then how will your end point know if the user is logged in? You need to provide an authentication header – David Anthony Acosta Feb 01 '18 at 19:30
  • @DavidAnthonyAcosta Can you tell, how to provide authentication header in my code? – Umair Jameel Feb 01 '18 at 19:58
  • well that depends on what your back end expects. It's done the same way, for example new HttpHeaders({'Authorization': 'some token here'}); Then your back end will use that to determine if the user is authenticated or not. But it's more complex than that. – David Anthony Acosta Feb 01 '18 at 20:00

1 Answers1

0

Your issue is that you need to pass in authorization headers.

let headers = new HttpHeaders({'Authorization', btoa(<your login information here>)});
return this.http.get(this.serviceUrl, {headers: headers});
Mike Tung
  • 4,735
  • 1
  • 17
  • 24