我制作了一个通用的拦截器,用于为每个请求在标头中打入授权令牌。令牌已从Spring Boot后端正确保存到会话存储中。相同的令牌在Postman中工作,但在Angular服务中会失败(从Spring Boot调用REST API时)。在浏览器控制台中,它显示HTTP 500 invalid token
任何帮助。
JwtInterceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class JwtInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
// tslint:disable-next-line:prefer-const
const token = sessionStorage.getItem('token');
if (token) {
request = request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + token)
});
}
return next.handle(request);
}
}
答案 0 :(得分:0)
令牌可能已过期 这就是我在代码中所做的
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization",localStorage.getItem("token") );