我安装了@ auth0 / angular-jwt的1.0.0版本,因为我在Angular 5.2上,我的登录设置了令牌,我可以在本地存储中看到它。但是,当我通过http发布帖子(该函数在下面称为addNote)时,我得到一个auth问题,看看我何时检查没有发送标头的请求。
这比较早,我想知道我是否安装了不同的版本。谢谢参观。
这是我的app.module.ts中的相关代码:
import { JwtModule } from '@auth0/angular-jwt';
import { HttpClientModule, HttpClient } from '@angular/common/http';
export function tokenGetter() {
return localStorage.getItem('token');
}
然后在我的导入中:
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
),
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:3001', 'http://localhost:8080', 'https://example.herokuapp.com/' ],
blacklistedRoutes: ['localhost:3001/auth/']
}
})
],
我的身份验证服务:
import { NgModule } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient, HttpHeaders } from '@angular/common/http';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable()
export class AuthService {
helper = new JwtHelperService();
constructor(private http: HttpClient, private router: Router){}
public isAuthenticated(): boolean {
const token = localStorage.getItem('token');
console.log("token:", localStorage.getItem('token'));
return !this.helper.isTokenExpired(token);
}
//Then we add the functions that allow users to register, authenticate, and logout
public login(credentials) {
console.log("login attempt", credentials);
this.http.post('https://example.herokuapp.com/api/login', credentials).subscribe(data => {
console.log("login attempt", data);
if(data){
localStorage.setItem('token', data['authToken']);
console.log("token in ", localStorage.getItem('token'));
this.router.navigate(['/notes']);
}
}, error => {
console.log(error);
if (error.status == 401) {
alert("Credentials are not matching: Username or Email is not correct");
}
if (error.status == 400) {
alert("Username or Email is missing");
}
});
}
public logout() {
localStorage.removeItem('token');
}
public register(user) {
this.http.post(' https://example.herokuapp.com/api/users', user).subscribe(data => {
console.log("new user! ", user.fullname)
if(data){
localStorage.setItem('token', data['authToken']);
console.log("token in ", localStorage.getItem('token'));
this.router.navigate(['/notes']);
}
}, error => {
console.log(error);
if (error.status == 422 || error.status == 400)
alert(error.error.message);
});
}
}
我的请求服务:
import { Injectable } from "@angular/core";
import { NOTES } from "./mock-data";
import { Note } from "./models";
import { BaseService } from "./base.service";
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class NotesService {
constructor(private http: HttpClient, private baseService: BaseService) { }
notesUrl = this.baseService.baseUrl + "/notes";
getNotes(): Observable<Note[]> {
return this.http.get<Note[]>(this.notesUrl);
}
addNote (note: Note): Observable<Note> {
return this.http.post<Note>(this.notesUrl, note, httpOptions).pipe(
tap((note: Note) => console.log(`added note w/ id=${note.id}`),
error => {
if (error.status == 400)
alert(error.error.message)
}
)
);
}
deleteNote (id: number): Observable<Note> {
console.log("deleting", id);
return this.http.delete<Note>(this.notesUrl + '/' + id, httpOptions).pipe(
tap((note: Note) => console.log(`deleted note w/ id=${id}`))
);
}
}