Angular 6 post form data with headers not working

12,947 views
Skip to first unread message

Selva Sajin

unread,
Jul 15, 2018, 12:18:29 PM7/15/18
to Angular and AngularJS discussion
Folks,
I am trying to send form data with headers in angular 6 but its not working, can anyone help me to resolve this?

here is my code:

Method 1:

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

offer = {'offerName':"Name",'discount':"10",'offerType':"grand"};

let headers = new HttpHeaders();
headers.append('token', 'VeTTgA7fDiwD2fWhQ');
headers.set('Token', 'VeTTgA7fDiwD2fWhQ');

const data = new FormData();
data.append('offer', JSON.stringify(this.offer));

this.HttpClient.post('http:host/app/api/offer', data, {headers: headers})
.subscribe(
(data:any) => {
console.log(data);
},
error => {
console.log(error);
}
);

Tried with headers.append and headers.set but unable to send any headers, My request headers (chrome's network tab) doesn't show my headers(token). But its showing the request payload(form data). The problem is with headers I am unable to send headers.


Method 2:

 import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data',
'token':'VeTTgA7fDiwD2fWhQ'
})
};

const data = new FormData();
data.append('offer', JSON.stringify(this.offer));

this.HttpClient.post('http:host/app/api/offer', data, httpOptions)
.subscribe(
(data:any) => {
console.log(data);
},
error => {
console.log(error);
}
);


This way doesn't worked at all, as am unable to see any request headers(chrome's network tab) and request payload(form data) as well.

I have done sending(post method) json data with headers which is working fine, but struggling to send form-data with headers

Zlatko Đurić

unread,
Jul 16, 2018, 2:18:05 AM7/16/18
to Angular and AngularJS discussion
Oh, a classic problem. I think the whole world has had this one, so don't feel bad about it :)

The thing is, headers are immutable. So, once you const headers = new Headers(), that's it - it stays empty. You have to either chain the headers or set new ones or it doesn't work.

Something like this:

    const headers = new HttpHeaders().set('Header', 'val').set('header2', 'val2');

Alternatively, you can always get a new instance, like this:

    let headers = new HttpHeaders();
    headers = headers.set('Header3', 'val3');
    headers = headers.set('Header4', 'val4');

And finally, if you do this in a HttpInterceptor, you can clone the request with a set of new headers:

    intercept(req, next) {
        req = req.clone({
            headers: req.headers.set('Header5', 'val5')
        })
    }

But this is a variation of a previous method.


And look into the network tab to see the headers set.
Reply all
Reply to author
Forward
0 new messages