无法访问错误响应的标题

时间:2018-12-21 07:17:51

标签: angular

在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;
}

1 个答案:

答案 0 :(得分:1)

我找到了答案。出于安全原因,浏览器不允许读取自定义标头。 XmlHttpRequest明确将其声明为错误,但是Angular宁愿忽略此问题,并仅为请求的标头键返回null。服务器需要发送Access-Control-Expose-Headers标头,以使浏览器允许代码访问这些标头。详细说明可以在这里找到:Unable to read custom http headers in javascript onreadystatechange?