Reputation: 1354
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:
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:
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:
undefined
, null
, multipart/formdata
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!
Upvotes: 2
Views: 473
Reputation: 1354
I was not able to find concrete solution for this, so a quick fix that resolved this issue was to:
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