Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I`m trying to access a URL with Basic Authentication.

The URL returns JSON data.

How can I add my username and password to this http request below?

private postsURL = "https://jsonExample/posts";

getPosts(): Observable<AObjects []>{
    return this.http.get<AObjects[]>(this.postsURL); 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

Refer to https://angular.io/guide/http or https://v6.angular.io/guide/http#adding-headers

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('username:password')
  })
};

Then use the headers:

return this.http.get<AObjects[]>(this.postsURL, httpOptions); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...