angular 5 httpclient,在post上,响应不返回自定义标头,仅返回响应对象

时间:2018-11-19 20:34:07

标签: angular angular-httpclient custom-headers csrf-token

在使用Angular 5常见的httpClient进行http发布调用时,我没有得到实际的http标头。我正在传递观察:请求中的“响应”以获取完整响应(默认情况下,httpClient仅返回响应正文)。

我想从http标头响应中读取csrftoken值。我可以看到使用chrome浏览器网络视图的响应标头中提供了csrftoken。

但是当我在Angular中读取httpClient响应时,此功能不可用。

 post(inURL, data, config = undefined) {
    let headers, options;
    if (config){
        options = config;
    } else {
        //headers = this.getDefaultHeader();
        //options = new RequestOptions({ headers: headers });
        options = httpOptions;
    }
    options = { ...options, observe: 'response' };

    let action = this.httpService.post(inURL, data, options);
    return new Promise((resolve, reject) => {
        action.subscribe(
            response => resolve(response),
            error => {
                this.interceptError(error);
                reject(error);
            }
        );
    });

} enter image description here

在chrome调试器上进行调试时,响应标头对象看起来像这样,因为您看到csrftoken不能用作响应对象上的键

enter image description here

这是我访问httpheaders的条件

   let headers: HttpHeaders = response.headers;
    if (headers && headers['csrftoken']) {
        let token: String = headers.get('csrftoken');
    }

1 个答案:

答案 0 :(得分:3)

正如注释中已经建议的那样,您无法检查标头是否以您的方式存在。您需要使用has方法。您的代码应如下所示:

let headers: HttpHeaders = response.headers;
if (headers && headers.has('csrftoken')) {
   let token: String = headers.get('csrftoken');
}
相关问题