个人资料页面未经授权(GET 401)

时间:2019-03-23 07:15:17

标签: node.js angular rest

我正在尝试创建一个普通应用程序,并且正在使用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未经授权。

1 个答案:

答案 0 :(得分:0)

我认为您需要为授权添加“ bearer” +令牌

像这样:

const httpOptions = {
  headers: new HttpHeaders ({
    'Authorization': `Bearer ${this.authTokenStudent}`,
    'Content-Type': 'application/json'
  }),
};

return this.http.get<data>('http://localhost:3000/users/profile/student', httpOptions).map(res => res);