簡體   English   中英

GET 請求 401(未經授權)

[英]GET Request 401 (Unauthorized)

在 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.loadToken() 會返回令牌。 您必須等到 this.loadToken() 函數返回 authToken。

為此,您可以使用 async 並等待您的函數,否則只需從 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;
  }

不確定這會有所幫助,但請嘗試在您的 WebAPI 項目中啟用 CORS:

WebApiConfig.cs (Register Method)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM