ПОЛУЧИТЬ запрос 401 (неавторизованный) - PullRequest
0 голосов
/ 10 марта 2019

В Почтальоне профиль авторизован, и возвращается объект 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;
    });
  }

}

Ответы [ 2 ]

0 голосов
/ 10 марта 2019

Не уверен, что это поможет, но попробуйте включить CORS в вашем проекте WebAPI:

WebApiConfig.cs (Register Method):

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
0 голосов
/ 10 марта 2019

это происходит потому, что 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;
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...