在 Angular 中设置 headers 5

Setting headers in Angular 5

我有一个登录用户的功能,响应为我提供了 body 中的令牌,我在 headers 中设置了它。

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']);
                    }

                })
            );
    }

然后,当我尝试使用那些 header 发送注销请求时,我发现 'x-auth' header 不存在。但是我明明是在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 调用时发送到服务器的 header(请注意我那里没有 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:

Side-note:我的 back-end 设置为拦截 req.headers['x-auth'] 并使用它登录(在 auth 中间件中)。 任何帮助将不胜感激。

HttpHeaders 不可变 - 它不会改变,必须重新分配。

将行更改为:

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

在你的删除函数中:

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

它应该可以工作。