簡體   English   中英

在Angular 5中設置標題

[英]Setting headers in Angular 5

我有一個登錄用戶的函數,響應給了我主體中的令牌,該令牌是在標題中設置的。

this.headers = new HttpHeaders({'Content-Type': 'application/json'});


loginUser(email, password) {
        const body = {email, password};
        return this.http.post(`${this.serverUrl}/users/login`, body, {
            observe: 'response',
            headers: this.headers
        })
            .pipe(
                tap(res => {
                    if (res.body['token']) {
                        this.jwtToken = res.body['token'];
                        this.headers.set('x-auth', this.jwtToken);
                        this.router.navigate(['/firms/create']);
                    }

                })
            );
    }

然后,當我嘗試使用這些標頭發送注銷請求時,我發現不存在“ x-auth”標頭。 但我清楚地在loginUser函數中進行了設置。

這是我的注銷功能:

   logoutUser() {
        return this.http.delete(`${this.serverUrl}/users/me/token`, {
            observe: 'response',
            headers: this.headers
        })
            .pipe(
                tap(res => {
                    this.headers.delete('x-auth');
                    this.removeTokenFromLocalStorage(this.jwtToken);
                    this.jwtToken = null;
                })
            );
    }

這些是我在LOGOUT調用中發送給服務器的標頭(請注意,盡管我應該這樣做,但那里沒有x-auth!)

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:
Connection:keep-alive
Content-Type:application/json
Host: censored
Origin:http://evil.com/
Referer:http://localhost:4200/somendpoint
User-Agent:

旁注:我的后端設置為攔截req.headers ['x-auth']並使用它登錄(在auth中間件中)。 任何幫助,將不勝感激。

HttpHeaders不可變的 -不變,必須重新分配。

將行更改為:

this.headers = this.headers.set('x-auth', this.jwtToken);

並在您的刪除功能中:

this.headers = this.headers.delete('x-auth');

它應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM