我正在尝试使用基本认证访问URL。
该URL返回JSON数据。
我该如何将我的用户名和密码添加到以下HTTP请求中?
private postsURL = "https://jsonExample/posts";
getPosts(): Observable<AObjects []>{
return this.http.get<AObjects[]>(this.postsURL);
}
我正在尝试使用基本认证访问URL。
该URL返回JSON数据。
我该如何将我的用户名和密码添加到以下HTTP请求中?
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);
http.get()
?你是否使用了任何与不同方法相关的头信息,例如预检请求? - Daniel W.我不知道您在获得授权后想要做什么,但是要使用基本身份验证进行简单调用以获得授权,您需要像这样操作:
let authorizationData = 'Basic ' + btoa(username + ':' + password);
const headerOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': authorizationData
})
};
this.http
.get('{{url}}', { headers: headerOptions })
.subscribe(
data => { // json data
console.log('Success: ', data);
},
error => {
console.log('Error: ', error);
});
import { HttpHeaders } from '@angular/common/http';
const username = 'JohnDoe'
const password = 'JonhnsSecret'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + token)
})
};
return this.http.get<AObjects[]>(this.postsURL, httpOptions);
post
方法替代get
方法吗?如果你正在使用get
方法,则应将凭据附加到请求头中。 - komron