1
votes

I'm not getting the actual http headers when making the http post call using Angular 5 common httpClient. I'm passing observe: 'response' in request to get the full response (by default httpClient returns only the body in response).

I want to read the csrftoken value from http header response. I can see that csrftoken is available in response headers using chrome browser network view.

But the same is not available when I read the httpClient response in Angular.

 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

and the response headers object looks like this while debugging on chrome debugger, as you see the csrftoken is not available as a key on the response object

enter image description here

Here is what i have for accessing the httpheaders

   let headers: HttpHeaders = response.headers;
    if (headers && headers['csrftoken']) {
        let token: String = headers.get('csrftoken');
    }
1
Have you at least tried to get the token out of the HttpHeaders object? Show that code.JB Nizet
@JBNizet added code to access teh httpheadersobject and updated the postlooneytunes
Here's the documentation of HttpHeaders: angular.io/api/common/http/HttpHeaders. It's not a POJO. Use headers.has('csrftoken').JB Nizet
awesome , that worked , thanks @JBNizetlooneytunes

1 Answers

3
votes

As already suggested in the comments you cannot check if a header exists the way you are doing it. You need to use the has method. Your code should look like this:

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