【问题标题】:How to read the token from header response in Angular 2?如何从 Angular 2 中的标头响应中读取令牌?
【发布时间】:2017-06-28 15:02:58
【问题描述】:

我的团队使用 Spring Boot 开发了一个 REST 服务。任务是构建一个登录模块。授权在后端完成。令牌在后端提供给令牌的“授权”字段。

现在我想从 angular 2 读取这个令牌。

我拥有的是:

  authenticateUser(user: ILogin): Observable<Response> {

    const url = `${this.baseUrl2}`

  //  console.log("the username after service is " + user.username + " and the password is " + user.password)

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log("the json format is " +JSON.stringify(user));

    return this.http.post(url, JSON.stringify(user))
                    .map((response: Response) => {

                        let userJson = response.headers;

                        console.log("the token is" +userJson.token); // here I got a type error and the error is that there is no token as the field of headers. 


        })
                   .do(data => console.log('authenticateuser:' + JSON.stringify(data)))
                   .catch(this.handleError);

}

我正在尝试在 Google 上进行搜索,但没有找到任何方法可以从标头中读取令牌。有人可以帮我吗?

P.S:如果我修改我的代码,我可以读取令牌

let userJson = response.headers;

到

let userJson = response.json().token

但问题是,在后端,令牌放在标题上,如果我如上所述更改我的代码,这意味着我正在寻找正文的令牌,如果我编译代码,则会出现运行时错误。

【问题讨论】:

  • 那么...如果您可以读取标头和令牌,有什么问题?

标签: angular http-headers token


【解决方案1】:
authenticateUser(user: ILogin): Observable<Response> {    
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log("the json format is " +JSON.stringify(user));

    return this.http.post(url, JSON.stringify(user))
                   .do((data:response) => {console.log(data.headers.get('token'))}))
                   .map((response: Response) => <any> response.json())
                   .catch(this.handleError);
}

【讨论】:

  • 如果你能解释一下你的代码会更好。
猜你喜欢
  • 1970-01-01
  • 2021-07-29
  • 2016-02-24
  • 2017-07-07
  • 2021-04-20
  • 2020-07-05
  • 2017-12-10
  • 2019-12-25
  • 2018-06-19
相关资源
最近更新 更多