Aakash Goplani
Aakash Goplani

Reputation: 1354

Error in mapping FormData structure Angular

I am trying to convert AJAX jQuery call with Angular HTTP POST request.

This is snippet of ajax jQuery

$.ajax({
   url: env.URL,
   data: request,
   method: 'POST',
   timeout: 6000,
   success: function (response) {
     // business logic
   }
});

This is the structure of request headers and body:

enter image description here

Response received back is an HTML form.

Converting this to Angular:

const header = new HttpHeaders();
header.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
header.append('Access-Control-Allow-Origin', '*');
header.append('Accept', 'text/html, application/xhtml+xml, */*');
const httpOptions = {
   responseType: 'text' as 'json', // if not converted, I get json parse error as return response is HTML e.g. error parsing `<` at line 28
   headers: header
};
const temp = new FormData();
Object.keys(request).forEach(key => temp.append(key, request[key]));

return this.http.post(env.URL, temp, httpOptions);

This is the structure of request headers and body:

enter image description here

In header, I have additional string getting inferred as boundary=----WebKitFormBoundaryGEf4TefkXkO6MbyV also in form-data

------WebKitFormBoundaryGEf4TefkXkO6MbyV
Content-Disposition: form-data; name="address"

test test test

I have tried multiple permutation and combinations with header values and responseType like:

Can you please help me fix structure of form data & content-type header sent in request!

Upvotes: 2

Views: 473

Answers (1)

Aakash Goplani
Aakash Goplani

Reputation: 1354

I was not able to find concrete solution for this, so a quick fix that resolved this issue was to:

  • change POST request call to a GET request
  • convert (form-data) payload to query params in URL:
const header = new HttpHeaders();
header.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

let queryParams = new HttpParams();
Object.keys(request).forEach(key => {
   queryParams = queryParams.append(key, request[key]);
});

const httpOptions = {
  responseType: 'text' as 'json',
  headers: header,
  params: queryParams
};

return this.http.get(env.URL, httpOptions);

Upvotes: 0

Related Questions