【问题标题】:Setting headers in Angular 5在 Angular 5 中设置标题
【发布时间】:2018-01-30 00:19:52
【问题描述】:

我有一个登录用户的函数,响应给我正文中的令牌,我在标题中设置。

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 中间件中)。 任何帮助将不胜感激。

【问题讨论】:

标签: javascript node.js angular angular5


【解决方案1】:

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

将行改为:

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

在你的删除功能中:

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

它应该可以工作。

【讨论】:

  • 解决了!谢谢。我以前写过应用程序,以前只设置标题,我没有想到 HttpHeaders 是不可变的。再次感谢。
猜你喜欢
  • 2019-01-29
  • 2018-01-27
  • 1970-01-01
  • 2018-05-17
  • 2018-07-08
  • 2018-08-17
  • 1970-01-01
  • 2018-09-06
  • 2018-09-14
相关资源
最近更新 更多