本文介绍了Angular 6 HTTP使用HTTP基本身份验证获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用基本身份验证访问URL.
I`m trying to access a URL with Basic Authentication.
URL返回JSON数据.
The URL returns JSON data.
如何在下面的http请求中添加用户名和密码?
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);
}
推荐答案
请参阅 https://angular.io/guide/http 或 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')
})
};
然后使用标题:
return this.http.get<AObjects[]>(this.postsURL, httpOptions);
这篇关于Angular 6 HTTP使用HTTP基本身份验证获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!