Arn*_*tre 13 typescript angular angular-httpclient
对于学校项目,我需要使用Angular创建一个简单的登录页面.单击登录按钮时,我需要在帖子中添加Authorization标头.我创建了一个后端,当我使用邮递员将我的授权值发布到该后端时,它的工作方式与后端没有任何问题.当我尝试使用我的前端发布到同一个后端时,它不起作用.向帖子添加标题的最佳方法是什么?似乎意见分歧.这是我的代码:
export class LoginComponent{
title = 'Login';
email = '';
password = '';
credentials = '';
basic = '';
constructor(private http:HttpClient){
}
createAuthorizationHeader(headers:Headers,basic){
headers.append('Authorization',basic);
}
login(event){
this.email = (<HTMLInputElement>document.getElementById("email")).value;
this.password = (<HTMLInputElement>document.getElementById("password")).value;
this.credentials = this.email + ":" + this.password;
this.basic = "Basic " + btoa(this.credentials);
console.log(this.basic);
let headers = new Headers();
headers.append('Content-Type','application/json');
headers.append('Authorization',this.basic);
let options = new RequestOptions({headers:headers});
console.log(headers);
return this.http.post('http://localhost:8000/api/v1/authenticate',options)
.subscribe(
res =>{
console.log(res);
},
err => {
console.log(err.message);
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行该代码时,我得到400状态响应并且不添加标头.
Kir*_*kin 29
HttpClient.post期望第二个参数是POST请求的主体.在你的例子中,你提供的Headers是身体,这不是你想要的.您可以使用以下方法正确提供标头:
return this.http.post('http://localhost:8000/api/v1/authenticate', null, options);
Run Code Online (Sandbox Code Playgroud)
我已经null在示例中显示了正文,但您可能希望以某种形式包含email和password属性.
编辑:你是混合Http和HttpClient.如果您要使用HttpClient(现在是推荐的方法),您需要放弃RequestOptions并Headers支持HttpHeaders.这变为:
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': this.basic });
let options = { headers: headers };
Run Code Online (Sandbox Code Playgroud)
其余代码与我上面显示的相同.重要的是要注意你的createAuthorizationHeader函数将需要使用并返回一个,HttpHeaders因为这个类是不可变的,并且append每次调用它时都会返回一个新对象.
您将需要导入HttpHeaders的@angular/common/http.
| 归档时间: |
|
| 查看次数: |
35014 次 |
| 最近记录: |