【问题标题】:GET Request 401 (Unauthorized)GET 请求 401(未经授权)
【发布时间】: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 项目中这样做?

标签: node.js angular rest


【解决方案1】:

发生这种情况是因为 this.loadToken() 将令牌返回给您。您必须等到 this.loadToken() 函数返回 authToken。

为此,您可以为您的函数使用 async 和 await,或者只返回 this.loadToken 中的值,如

getProfile() {
    let headers = new HttpHeaders();
    this.authToken = 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');
     return Token;
  }

【讨论】:

  • 进行了更改,但不起作用。仍然遇到同样的错误
【解决方案2】:

不确定这是否会有所帮助,但请尝试在您的 WebAPI 项目中启用 CORS:

WebApiConfig.cs (Register Method):

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

【讨论】:

  • 项目中启用了CORS,该应用程序前几天可以正常工作。但是我使用的是不推荐使用的包,所以我升级了 CLI 并从头开始。现在它不工作了,我认为应用程序的前端有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 2021-04-26
  • 2017-11-13
相关资源
最近更新 更多