美文网首页前端小乐趣
angular HttpClient :如何从响应的标头获取值

angular HttpClient :如何从响应的标头获取值

作者: MAYDAY77 | 来源:发表于2023-01-12 17:32 被阅读0次

    一、前端代码部分:

    1、需要在HttpService中post的配置项中添加observe:'response'

    post(url:string, body:any |null, options: {

            headers?: HttpHeaders | {

                    [header:string]:string |string[];

            };

            observe:'response';

            params?: HttpParams | {

                    [param:string]:string |string[];

            };

            reportProgress?:boolean;

            responseType?:'json';

            withCredentials?:boolean;

    }): Observable>;

    请仔细研究上述post请求的配置项option,具体配置如下:

    _post_form(url:string, body:any): Observable {

                return this.http.post(url, body, {reportProgress:true, observe:'response'})

                .pipe(retry(0), catchError((err) =>this.handleError(err, this.router)));

     }

    要注意!!!observe:'response'设置后,接口响应拿到的是包含status,statusText,body等的全部响应信息,取值时要注意用result.body才能拿到要的内容。

    2、获取响应头参数方法, res为接口响应,resHeader为要获取的响应头的标头名称(小写)

    this.commonService.getResponseHeaders(result, 'content-disposition');

    getResponseHeaders(res, resHeader) {

              const keys = res.headers.keys(); // 获取响应头各参数名数组

              const headers = keys.map(key =>`${key.toLowerCase()}:${res.headers.get(key)}`); // 获取响应头各参数名及参数值的数组

              let resHeaderContent ='';

              if (resHeader && headers && headers.length) {

                    headers.forEach((head) => {

                            if (head.indexOf(resHeader) != -1) {

                                    resHeaderContent = head.split(':')[1];

                              }

                    });

              }

              return resHeaderContent;

    }

    贴出keys和headers的打印值(key.toLowerCase(),是因为谷歌的key打印出来都是小写开头,而IE是大写开头,这里要统一处理为小写)

    二、后端代码部分:

    Access-Control-Expose-Headers响应报头指示哪些报头可以公开

    如果客户端获取到想要的请求头,则必须使用Access-Control-Expose-Headers 列出他们。

    相关文章

      网友评论

        本文标题:angular HttpClient :如何从响应的标头获取值

        本文链接:https://www.haomeiwen.com/subject/ulrwcdtx.html