【发布时间】:2018-06-23 11:09:03
【问题描述】:
我在服务器端遇到问题,当我刷新页面时,无法从本地存储中检索服务器上的 jwt 令牌,因为本地存储仅存在于浏览器中。另外,当我登录时,我将令牌保存在传输状态,并在页面刷新后状态变量再次消失,这是正常行为吗?这个问题有解决办法吗?
这是我的拦截器:
import { Injectable, Injector, Inject, PLATFORM_ID } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { isPlatformServer, isPlatformBrowser } from '@angular/common';
const AUTH_STATE = makeStateKey<string>('authState');
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
private isServer: boolean;
constructor(private tstate: TransferState, @Inject(PLATFORM_ID) private platformId) {
this.isServer = isPlatformServer(platformId);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
let authReq: any = req;
if (this.tstate.hasKey(AUTH_STATE)) {
// We are in the browser
authReq = req.clone(
{
headers: req.headers.set("Auth", this.tstate.get(AUTH_STATE, ''))
}
);
console.log("CLIENT")
console.log(this.tstate.get(AUTH_STATE, ''))
} else if (this.isServer) {
// We are on the server
authReq = req.clone(
{
headers: req.headers.set("Auth", "fromServer")
}
);
console.log("SERVER")
} else {
// State not transfered
let token: any;
token = window.localStorage.getItem("token");
if (token) {
authReq = req.clone(
{
headers: req.headers.set("Auth", token)
})
this.tstate.set(AUTH_STATE, token);
}
console.log("BROWSER")
}
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(authReq)
.catch((error, caught) => {
//intercept the respons error and displace it to the console
console.log("Error Occurred");
console.log(error);
//return the error to the method that called it
return Observable.throw(error);
}) as any;
}
}
这部分:headers: req.headers.set("Auth", "fromServer") "fromServer" 应替换为本地存储中的正确令牌...
【问题讨论】:
标签: local-storage angular5 angular-universal angular-http-interceptors