У меня проблемы с входом в это простое приложение MEAN - PullRequest
1 голос
/ 14 апреля 2020

Я пытаюсь создать это простое стековое приложение MEAN с простой функциональностью регистрации, входа в систему и просмотра профиля.

Итак, где возникает ошибка? Он появляется, когда этот новый ie кодер пытается войти в это простое приложение

Вот его скриншот

enter image description here

Вот коды, чтобы вы могли увидеть ошибки, которые я мог совершить.

Это код, принадлежащий компоненту входа в систему

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router'
import { FlashMessagesService } from 'angular2-flash-messages';
import { Observable } from 'rxjs/Rx';
import { map, subscribeOn } from 'rxjs/operators';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username: String;
  password: String;

  constructor(
    private authService: AuthService,
    private router: Router,
    private flashMessage: FlashMessagesService
  ) { }

  ngOnInit(): void {
  }

  onLoginSubmit() {

    console.log(this.username, this.password);

    const user = {

      username: this.username,
      password: this.password
    }

    this.authService.authenticateUser(user).subscribe(data => {

      console.log(data);



      if (data) {



        this.authService.storeUserData(data.token, data.user);


        this.flashMessage.show('You are now logged in', {
          cssClass: 'alert-success',
          timeout: 5000
        });


        this.router.navigate(['/dashboard']);

      }
      else {

        this.flashMessage.show('incorrect information you stupidass', {
          cssClass: 'alert-danger',
          timeout: 5000
        });

        this.router.navigate(['/login']);

      }




    });
  }

}

Следующий файл относится к файлу службы аутентификации

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';
import { tokenNotExpired } from 'angular2-jwt';


@Injectable({
  providedIn: 'root'
})
export class AuthService {



  authToken: any;
  user: any;

  constructor(private http: Http) { }

  registerUser(user: { name: String; email: String; username: String; password: String; }) {

    let headers = new Headers();
    //adding a value to the header and connecting to the backend
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/register', user, { headers: headers }).pipe(map((res: { json: any; }) => res.json));


  }


  authenticateUser(user: { username: String; password: String; }) {

    let headers = new Headers();
    //adding a value to the header and connecting to the backend
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/users/authenticate', user, { headers: headers }).pipe(map((res: { json: any; }) => res.json));

  }


  getProfile() {

    let headers = new Headers();
    this.loadToken();
    headers.append('Authroization', this.authToken);
    //adding a value to the header and connecting to the backend
    headers.append('Content-Type', 'application/json');
    return this.http.get('http://localhost:3000/users/profile', { headers: headers }).pipe(map((res: { json: any; }) => 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;
  }

  loggedIn() {

    return tokenNotExpired(null, localStorage.getItem('id_token'));
  }


  logout() {

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

}
//this.myObservable().pipe(map(data => {}))

И последний из файла app.component

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';


import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { ProfileComponent } from './components/profile/profile.component';
import { JwtModule } from '@auth0/angular-jwt';
import { FormsModule } from '@angular/forms';


import { ValidateService } from './services/Validate.service';
import { FlashMessagesModule } from 'angular2-flash-messages';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './guards/auth.guard';

export function tokenGetter() {
  return localStorage.getItem('access_token');
}

const appRoutes: Routes = [

  { path: '', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
]

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    LoginComponent,
    RegisterComponent,
    HomeComponent,
    DashboardComponent,
    ProfileComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes),
    FlashMessagesModule.forRoot(),
    JwtModule.forRoot({
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains: ['localhost:4000'],
        blacklistedRoutes: ['localhost:4000/api/auth']
      }
    })
  ],
  providers: [ValidateService, AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

Почему возникает эта ошибка?

Редактировать: Ниже приведен скриншот запросов почтальона, которые Я сделал для этого приложения. Там вы также можете найти значение токена.

Запрос аутентификации - это то, что вы видите здесь:

authentication

Далее один для запроса на получение, чтобы войти в профиль:

profile

...