Unauthorized 401 error GET http://localhost:3000/users/profile 401 (Unauthorized)

Discussão em 'Angular' iniciado por KISHOR KUMAR SN, Dezembro 1, 2024.

  1. I was trying to get user information on profile page but it is showing GET http://localhost:3000/users/profile 401 (Unauthorized). Please find the image on below link which i getting. enter image description here Here the code which i using in three files.

    This is auth.service.ts

    import { Injectable } from '@angular/core';
    import {Http, Headers} from '@angular/http';
    import 'rxjs/add/operator/map';

    @Injectable()
    export class AuthService {

    authToken: any;
    user: any;

    constructor(private http:Http) { }

    registerUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/register', user,{headers: headers})
    .map(res => res.json());
    }

    authenticateUser(user){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user,{headers: headers})
    .map(res => res.json());
    }

    getProfile(){
    let headers = new Headers();
    this.loadToken();
    headers.append('Autherization', this.authToken);
    headers.append('Content-Type', 'application/json');
    return this.http.get('http://localhost:3000/users/profile',{headers: headers})
    .map(res => res.json());
    }

    storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
    }

    loadToken(){
    const token = localStorage.getItem('id_token');
    this.authToken = token;
    }

    logout(){
    this.authToken = null;
    this.user = null;
    localStorage.clear();
    }
    }


    This is 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.getProfile().subscribe(profile => {
    this.user = profile.user;
    },
    err => {
    console.log(err);
    return false;
    });
    }

    }


    This is profile.component.html

    <div *ngIf="user">
    <h2 class="page-header" >{{user.name}}</h2>
    <ul class="list-group">
    <li class="list-group-item">Username: {{user.username}}</li>
    <li class="list-group-item">Email: {{user.email}}</li>
    </ul>
    </div>

    Continue reading...

Compartilhe esta Página