Error in mapping FormData structure Angular

Viewed 165

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:

  • not sending headers at all and let it get inferred by default as per standards
  • Set content-type to undefined, null, multipart/formdata
  • set responseType just to text (gives error), omitting responseType (gives error again) i.e. Types of property 'responseType' are incompatible. Type 'string' is not assignable to type '"json"'. as returned response is HTML.

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

1 Answers

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);
Related