【问题标题】:Cannot access headers of the error response无法访问错误响应的标头
【发布时间】:2018-12-21 17:46:30
【问题描述】:

在 Angular 6 中,我无法获取 http 错误响应的标头。例如,服务器返回状态代码 401,但在此错误响应中还包含额外的标头。这样做的正确方法是什么?

log(url:string){
    let res = this.http.get<any>(url,  httpOptions) as Observable<HttpResponse<any>>;
    res.subscribe(
        (data: any) => {console.log(data.headers.get('WWW-Authenticate'))}, // success path
        error =>{console.log(error.headers.get('WWW-Authenticate'))} // error path
     );
}

private getHttpOptions():any {

    const headers = {};
    headers['Content-Type'] = 'application/json';
    headers['Authorization'] = "Bearer " + "123";

    const httpOptions = {headers: new HttpHeaders(headers), 
                         observe: "response"
                         };
    return httpOptions;
}

【问题讨论】:

  • 你能分享一下你期望什么标题以及你得到什么?
  • @HaseebAhmed 我正在尝试获取“WWW-Authenticate”标头,但枚举收到的标头键也会导致空数组。

标签: angular


【解决方案1】:

我找到了答案。由于安全原因,浏览器不允许读取自定义标头。 XmlHttpRequest 明确指出这是错误,但显然 Angular 更喜欢沉默这个问题,并简单地为请求的标头键返回 null。服务器需要发送Access-Control-Expose-Headers 标头,以便浏览器允许代码访问这些标头。详细解释可以看这里:Unable to read custom http headers in javascript onreadystatechange?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2021-01-22
    • 2016-02-13
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多