【发布时间】:2019-03-10 15:01:32
【问题描述】:
在 Postman 中,配置文件被授权并返回一个 json 对象。 但是在前端,我收到了这个错误。
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:3000/users/profile", ok: false, ...}
这是我的 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: any;
}
export class AuthService {
authToken: any;
user: any;
constructor(private http: HttpClient) { }
getProfile() {
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get<data>('http://localhost:3000/users/profile', {headers: headers})
.map(res => res);
}
loadToken(){
const Token = localStorage.getItem('id_token');
this.authToken = Token;
}
}
profile.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.getProfile().subscribe(profile => {
this.user = profile.user;
},
err => {
console.log(err);
return false;
});
}
}
【问题讨论】:
-
尝试控制
this.authToken的值并在网络选项卡中检查请求! -
@PrashantPimpale 试过这样做,我得到了正确的令牌,它适用于邮递员但不适用于应用程序。
-
我认为它与
CORS有关,您是否允许在 webAPI 项目中这样做?