HTTP post appends null to the data


#1

I have this data coming from form using <form #form=“ngForm” (ngSubmit)=“myFunction(form.value)”>

I am sending the form value to HTTP post method as

myFunction(formData){
let headers = new HttpHeaders({
‘Content-Type’: ‘application/x-www-form-urlencoded’,
});
return new Promise( resolve => {
this.http.post(this.my_api, formData, { headers: headers})
.subscribe( data => {
resolve(data);
});
});
}

When i console the form.data, i get

{name: ‘myname’, address:‘myaddress’}

But
what i get in the api is

{{“name”:“myname”, “address”:“myaddress”} : null }

which is making me hard to get the values in my backend.

P.S. I am using Laravel as Backend

Why is that : null is getting appended to the request?
How to get the values in the Laravel backend?


#2

Don’t make headers objects and don’t instantiate promises.

The type of object you pass as a payload to the post call determines the content type. If it’s a PODO, the content type will be application/json. If it’s an instance of HttpParams, the content type will be application/x-www-form-urlencoded.

If you control the backend, the easiest solution would be to change it to accept JSON, at which point your client code becomes as simple as:

return this.http.post(api, formData);

If you can’t do that, you will have to build up an HttpParams like so:

let body = new HttpParams();
for (let k in formData) {
  if (formData.hasOwnProperty(k)) {
    body = body.set(k, formData[k]);
 }
}
return this.http.post(api, body);