使用http拦截器和localstorage

时间:2018-01-14 17:57:54

标签: local-storage angular5 angular-universal angular-http-interceptors

我在服务器端遇到问题,当我刷新页面时,由于localstorage只存在于浏览器上,因此无法从本地存储中检索服务器上的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")&#34; fromServer&#34;应该用本地存储中的正确令牌替换......

1 个答案:

答案 0 :(得分:0)

您已经在this.isServer使用只想在服务器上运行的代码。对localStorage的任何使用都需要类似地包含在this.isBrowserif (isPlatformBrowser(this.platformId)) {}

正如您所说,您将无法在localStorage中存储令牌,然后在服务器端检索它。您可以将其包装在浏览器检查中,也可以将令牌存储在您可以阅读的位置(例如,数据库)。

请参阅此答案,了解另一种存储方式:How to use localStorage in angular universal?