【问题标题】:How to get response Header in Angular 8 for post request如何在 Angular 8 中为发布请求获取响应标头
【发布时间】:2020-05-14 22:17:19
【问题描述】:

如何在 Angular 8 中为发布请求获取响应标头并将 jwt 令牌存储在本地存储中

login(req): Observable<any> {
  return this.http.post(this.apiUrl + '/login', req).pipe(
    map(res => {
      if (res) {
        this.loggedIn.next(true);

      }
      return res;
    })
  );
}

【问题讨论】:

标签: angular


【解决方案1】:
loadToken() {
    const token = localStorage.getItem('token');
    this.authToken = token;
  }

createAuthHeader() {
    this.loadToken();
    const headers = new HttpHeaders().set(
      'Authorization',
      `Bearer ${this.authToken}`
    );
    return { headers };
  }

login(formData) {
    return this.http.post(`${this.url}/login`, formData,this.createAuthHeader());
  }

您需要将标头作为 post req 中的第三个参数传递。 参考这个例子。

【讨论】:

    【解决方案2】:

    要查看请求的响应标头,您需要在请求中使用observe: 'response' 选项:

    return this.http.post(this.apiUrl + '/login', req, { observe: 'response'}).pipe(
      map((response) => {
        const data = response.data; // the data returned from your request
        const keys = response.headers.keys(); // keys of the response headers
        const headers = keys.map((key) => response.headers.get(key)); // values of the response headers
    
        // So to get the token, you need to do
        const JWTtoken = response.header.get('JWT-TOKEN');
    
        // To store you do:
        localStorage.set('JWT-TOKEN', JWTtoken);
    
        return data;
      });
    );
    

    【讨论】:

    • 但我在 JWT-Token 中得到了 null
    • @akhilashok 检查密钥数组,以查看从 response.header.get() 获取的正确密钥。区分大小写
    • 0:“无缓存,无存储,必须重新验证”1:“应用程序/json;charset=UTF-8”2:“0”3:“无缓存”跨度>
    • 这些是我的密钥数组,你可以查看我昨天上传时的图像没有 jwt-token 的密钥
    • @akhilashok 您需要在服务器后端公开 JWT-TOKEN 标头。具体方法取决于您使用的服务器技术
    猜你喜欢
    • 2018-01-26
    • 2023-03-18
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    相关资源
    最近更新 更多