从Angular中的本地存储访问JWT(v5)

时间:2018-04-16 11:07:47

标签: angular local-storage jwt

访问auth route(我的个人资料页面)

后,我的标题出现以下错误
Status Code: 500 Internal Server Error and
x-access-token: myToken

,当我打开带有角度的受保护路线时。

如何使其与最佳解决方案协同工作: - 就像我可以从中解决问题的最小事情一样。 在此先感谢

我的app.module.ts文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';  // <-- #1 import module

import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { HomeComponent } from './components/home/home.component';
import { DashbaordComponent } from './components/dashbaord/dashbaord.component';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
import { ProfileComponent } from './components/profile/profile.component';


import { ConfigService } from './services/config.service';
import { AuthComponent } from './components/auth/auth.component';


const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'profile', component: ProfileComponent },
  { path: 'auth', component: AuthComponent },
  {
    path: 'dashboard',
    component: DashbaordComponent,
    data: { title: 'dashboard' }
  },
  { path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  { path: '**', component: HomeComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    HomeComponent,
    DashbaordComponent,
    LoginComponent,
    RegisterComponent,
    ProfileComponent,
    AuthComponent
  ],
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  providers: [ConfigService],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的Login.component.ts文件

import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../../services/config.service';
import { Config } from '../../interfaces/config';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  username: string;
  password: string;
  constructor(private configService: ConfigService,private router: Router) { }
  ngOnInit() {
  }
  config : Config;
  configs : any;
  myToken : any;
  logedConfig() {
    const newConfiged = {
      username: this.username,
      password: this.password,
      myToken : this.myToken
    };
    this.configService.logConfig(newConfiged)
     .subscribe(data => {
      if(data){
      this.configs = data;
      localStorage.setItem('token', data.myToken)
      this.router.navigate(['/dashboard']);
      } else{
      this.router.navigate(['/login']);
      }
    } );)  
  }
}

我的config.service.ts文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Config } from '../interfaces/config';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'x-access-token': 'myToken'
  })
};
@Injectable()
export class ConfigService {
  myToken : any;

  constructor(private http: HttpClient) { }
  configUrl = 'http://localhost:3000/api/users';
  postUrl = 'http://localhost:3000/api/register';
  deleteUrl = 'http://localhost:3000/api/user';
  loginUrl = 'http://localhost:3000/api/login';
  authUrl = 'http://localhost:3000/api/auth/profile';
  getConfig() {
    // now returns an Observable of Config
    return this.http.get<Config>(this.configUrl);
  }
  /** POST: add a new hero to the database */
  addConfig (config: Config): Observable<Config> {
    return this.http.post<Config>(this.postUrl, config, httpOptions)
  }
  deleteConfig (): Observable<{}> {
    // const url = `${this.deleteUrl}/${id}`; // DELETE api/heroes/42
    return this.http.delete(this.deleteUrl, httpOptions)
  }
  logConfig (config: Config): Observable<Config> {
    return this.http.post<Config>(this.loginUrl, config, httpOptions)
  }
 authConfig() {
    localStorage.getItem('token');
    return this.http.get<Config>(this.authUrl, httpOptions);
  }
}

我的auth.component.ts文件(在此文件中获取令牌)

import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../../services/config.service';
import { Config } from '../../interfaces/config';
import { Router } from '@angular/router';
@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {
  myToken :any;
  constructor(private configService: ConfigService,private router: Router) { }
  config: Config;
  configs : any;
  ngOnInit() {
    this.doConfig()
  }
  doConfig() {
    this.configService.authConfig()
      // clone the data object, using its known Config shape
      .subscribe(data => this.configs = data );
  }
}

我的auth.component.html文件:

<div class="jumbotron jumbotron-fluid">
  <div class="container text-center">
    <h1 class="display-4">Profile</h1>
    <button type="button" class="btn btn-danger">Do nothing</button>
    <p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
    <ul class="list-group" *ngFor="let config of configs">
        <li class="list-group-item">{{config.username}}  
        </li>

    </ul>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您正在发送静态字符串作为标记

 let Token= localStorage.getItem('token');
 const httpOptions = {
  headers: new HttpHeaders({
  'Content-Type':  'application/json',
  'x-access-token': Token
    })
  };
  http.get('/api/me', { headers: {'x-access-token': token} });
  return this.http.post<Config>(this.postUrl, config, httpOptions)