1

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');
    }
4
  • Have you at least tried to get the token out of the HttpHeaders object? Show that code. Commented Nov 19, 2018 at 21:18
  • @JBNizet added code to access teh httpheadersobject and updated the post Commented Nov 19, 2018 at 21:35
  • 1
    Here's the documentation of HttpHeaders: angular.io/api/common/http/HttpHeaders. It's not a POJO. Use headers.has('csrftoken'). Commented Nov 19, 2018 at 21:38
  • 1
    awesome , that worked , thanks @JBNizet Commented Nov 19, 2018 at 22:33

1 Answer 1

3

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');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.