Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 10 | Http post | String array append FormData

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.

like image 381
Roman Avatar asked Aug 10 '26 07:08

Roman


1 Answers

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));
like image 183
ForestG Avatar answered Aug 11 '26 20:08

ForestG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!