【发布时间】:2019-08-14 03:25:24
【问题描述】:
我正在尝试创建一个普通的应用程序,并且我正在使用 JWT 令牌进行身份验证。
用户配置文件的获取请求显示未经授权。但是当我通过邮递员发送 JWT 令牌时,它得到了授权。我认为我的前端 Angular 代码有问题。
我尝试控制台日志 this.authTokenStudent 和 this.loadToken() 这两个令牌正是同样,当我将该令牌复制到邮递员时,它会获得授权。
这是我的 auth.service.ts 文件:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
interface data{
success: boolean;
msg: string;
token: string;
user: Object;
teacher: any;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
authTokenStudent: any;
authTokenTeacher: any;
user: any;
teacher: any;
constructor(private http: HttpClient) { }
authenticateUser(user){
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post<data>('http://localhost:3000/users/authenticate/student', user, {headers: headers})
.map(res => res);
}
getStudentProfile() {
let headers = new HttpHeaders();
this.authTokenStudent = this.loadToken();
headers.append('Authorization', this.authTokenStudent);
headers.append('Content-Type', 'application/json');
return this.http.get<data>('http://localhost:3000/users/profile/student', {headers: headers})
.map(res => res);
}
loadToken(){
const studentToken = localStorage.getItem('student_id_token');
return studentToken;
}
}
这是我的 profile.component.ts 文件:
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private authService: AuthService,
private router: Router,
) { }
ngOnInit() {
this.authService.getStudentProfile().subscribe(profile => {
this.user = profile.user;
console.log(profile);
},
err => {
console.log(err);
return false;
});
}
}
auth.service.ts 中的身份验证用户正常工作并将用户登录,但由于错误:GET request 401 Unauthorized,无法显示配置文件信息。
【问题讨论】: