Я пытаюсь создать среднее приложение и использую токен 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 401 не авторизован.