I have an interceptor for adding the JWT to each request as follows:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { StorageService } from '../core/services/storage.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
token: string;
constructor(
private storageService: StorageService
) {
this.token = storageService.tokenString;
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.token) {
const addToken = req.clone({
headers: req.headers.set('token', this.token),
});
return next.handle(addToken);
} else {
return next.handle(req);
}
}
}
and it is then provided in the app.module.ts as follows:
providers: [
AuthGuard,
AdminGuard,
ManagerGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptor,
multi: true
}
]
this is resulting in a 304 error so the request url should look like this...
http://localhost:3000/api/users/getAllUsers?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NzA2LCJlbWFpbCI6InNhbmRyYUB0ZW5kZXNpZ24udXMiLCJpYXQiOjE1MjkyNzcxOTJ9.j6gOzGN02vvOPMKgtcFSaVkrm00bGCfqV8isCUVZKVs
and when i look in my network tab I can confirm that the token is not being added
答案 0 :(得分:0)
1) I think you are adding headers wrong
const addToken = req.clone({
headers: req.headers.set('token', this.token),
});
should be
const addToken = req.clone({
headers: {token:this.token},
});
2) You stated that
equest url should look like this... http://localhost:3000/api/users/getAllUsers?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NzA2LCJlbWFpbCI6InNhbmRyYUB0ZW5kZXNpZ24udXMiLCJpYXQiOjE1MjkyNzcxOTJ9.j6gOzGN02vvOPMKgtcFSaVkrm00bGCfqV8isCUVZKVs
It won't look like that with current codebase - you are adding headers in the interceptor, and your statement states that it should be added as query parameter
Also double check that this.token
is actually set in the interceptor as it is the condition of actual request modification - it might be falsy.