我在使用角度5进行发布请求时遇到问题。重试的令牌是正确的,如果我用邮递员测试我得到预期的数据。有人可以给我一个提示,也许我使用了错误的东西。
AuthService.ts
getProfile(){
this.loadToken();
let headers = new HttpHeaders();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this._http.get('http://localhost:8080/users/authenticate', {headers: headers}).map(res => res);
};
loadToken() {
console.log(this.authToken); //undefined here
this.authToken = localStorage.getItem('id_token');
console.log(this.authToken) // correct token here
}
ProfileComponent.ts
ngOnInit() {
this._authService.getProfile().subscribe(profile => {
console.log('1', profile);
this._router.navigate(['/profile'])
}, err => {
console.log(`Error`, err); // IT GOES STRAIGHT HERE
return false;
});
}
//ERROR OUTPUT
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://127.0.0.1:8080/users/profile", ok: false, …}
答案 0 :(得分:0)
它的工作原理如下:
let headers = new HttpHeaders().append('Authorization', this.authToken).append('Content-Type', 'application/json');
TANKS链接@LLai