Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular 8中获取post请求的响应头_Angular - Fatal编程技术网

如何在Angular 8中获取post请求的响应头

如何在Angular 8中获取post请求的响应头,angular,Angular,如何在Angular 8中获取post请求的响应头并将jwt令牌存储在localstorage中 login(req): Observable<any> { return this.http.post(this.apiUrl + '/login', req).pipe( map(res => { if (res) { this.loggedIn.next(true); } return res; })

如何在Angular 8中获取post请求的响应头并将jwt令牌存储在localstorage中

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

      }
      return res;
    })
  );
}
登录(req):可观察

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

要查看请求的响应标题,您需要使用请求中的选项:

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@akhilashok检查keys数组,查看要从
response.header.get()
获取的正确密钥。它区分大小写0:“无缓存,无存储,必须重新验证”1:“应用程序/json;charset=UTF-8“2:“0”3:“无缓存”这些是我的密钥数组,您可以在我昨天上传时查看图像jwt没有密钥-token@akhilashok您需要在服务器后端公开
JWT-TOKEN
头。如何操作取决于您使用的服务器技术
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;
  });
);