【问题标题】:Angular 4 How to read the token in the header?Angular 4 如何读取标头中的令牌?
【发布时间】:2018-02-13 18:20:22
【问题描述】:

我是 Angular 的新手。我无法读取 REST 服务响应标头中的令牌 (jwt)。如何阅读标题?这是我的代码:

    loginUser(loginUser:Login,callback: (data) => void){ 

        let body = JSON.stringify(loginUser)
        const headerJson = {
          'Content-Type': 'application/json'    
        }
        let options = { headers: new HttpHeaders( headerJson ) };
        return this.http.post(this.config.datiBean.urlLoginToken, body,options).subscribe(

          res =>{

            console.log("body :"+JSON.stringify(res)); //ok

            callback(res);
          }

          /// at this point how can I read headers?

        )};
}

我想阅读以下信息:

感谢您的帮助

【问题讨论】:

  • 看看angular.io/guide/http,它提到了您将如何阅读回复。
  • { 观察:'响应'}
  • 如果我插入返回 this.http.post (this.config.datiBean.urlLoginToken, body, {observe: "response"})。订阅(.....我从服务器 415(不支持的媒体类型)收到以下错误,因为服务器只接收 json 调用

标签: angular


【解决方案1】:

很可能我的方法不正确。我这样修改了我的方法:

    loginUser(loginUser:Login,callback: (data) => void){ 

       let creds = JSON.stringify(loginUser);
       let contentHeader = new HttpHeaders({ "Content-Type":"application/json" });
       this.http.post(this.config.datiBean.urlLoginToken, creds, { headers: contentHeader, observe: 'response' })
        .subscribe(
        (resp) => {
            console.log("TOKEN:  "+resp.headers.get('X-Auth'))
            console.log("body:  "+JSON.stringify(resp.body))
            callback(resp)
        },
        (resp) => {
            console.log("resp-error");
            console.log(resp);
        }
      );
  };

现在可以正常使用了

【讨论】:

    【解决方案2】:

    迭戈。

    如果您使用的是 NG4 和现已弃用的 http 类,那么我认为您应该尝试在订阅中收集键和值。 https://v4.angular.io/api/http/Headers#values

    但请注意,您将只能使用公开的标头。您可以使用Access-Control-Expose-Headers 包含这些人的列表。

    res =>{
      console.log("body :"+JSON.stringify(res)); //ok
      callback(res);
      headerKeys = res.headers.keys(); // this will provide an array of strings for the exposed headers
    }
    

    【讨论】:

    • 我不确定您是否尝试在订阅之外使用标头值,在这种情况下,当我输入代码时,您可以在订阅之外创建一个变量并使用 res 分配内部的值.头文件。无论如何,您必须在 access-control-expose-header 中指定 x-Auth 才能收集信息。我将尝试提供一个更好的代码示例。
    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 2017-09-22
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2019-07-22
    • 2020-07-05
    • 2018-10-13
    相关资源
    最近更新 更多