У меня установлена версия 1.0.0 @ auth0 / angular-jwt, так как я использую Angular 5.2, мой логин устанавливает токен, я вижу его в локальном хранилище.Однако, когда я захожу в пост (функция называется addNote ниже) через http, я получаю проблему с аутентификацией и вижу, когда проверяю запрос на отсутствие отправляемого заголовка.
Это работало ранее, мне интересно, была ли у меня установлена другая версия.Спасибо, что посмотрели.
вот соответствующий код в моем 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}`))
);
}
}