Reputation: 3941
I have to make a post request to an api endpoint, but I get an error status 500.
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
This is my code:
var selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selected[]', selectedIds);
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
The issue is in this line: sendData.append('selected[]', selectedIds);
I have no clue how to pass an array to FormData.
This is a working example from our android app. I need to convert this request in angular/typescript syntax:
@JvmSuppressWildcards
@FormUrlEncoded
@POST("APIENDPOINT")
fun addData(
@Field("auth") auth: String,
@Field("identifier") identifier: String,
@Field("selected[]") selected: ArrayList<String>
): Call<ResponseBody>
What I know so far:
It seems angular does not serialize the data, so I tried some hardcoded fixes, but none of these worked:
sendData.append('selected%5B%5D', '%2231%22');
sendData.append('selected%5B%5D', '31');
sendData.append('selected%5B%5D', 31);
sendData.append('selected%5B%5D', '%5B%2231%22%5D');
sendData.append('selected%5B%5D', selectedIds);
sendData.append('selected%5B%5D', JSON.stringify(selectedIds));
If I use selected
instead of selected[]
, then I get no error, but obviously no data is updated, so I am pretty sure it is a serialization/parsing issue.
Upvotes: 3
Views: 1913
Reputation: 2199
The statusCode 500
is the Internal Server Error, and it's the server-side problem. So, It's better to check the API
if it can receive your request or not.
FormData's append()
method accept string
or blob
type So you can use JSON.stringify()
method (formData.append('selectedIds', JSON.stringify(selectedIds));
). So try this:
let selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selectedIds', JSON.stringify(selectedIds));
this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
});
Upvotes: 1
Reputation: 18105
From this answer:
FormData's append() method can only accept objects of string or blob type. If you need to append the array, use JSON.stringify() method to convert your array into a valid JSON string.
formData.append('selected[]', JSON.stringify(selectedIds));
Upvotes: 2