Javascript – axios post array data

axioshttpjavascriptreactjs

I'm trying to send post request to a server I don't have much control on it. The only thing I know is I can obtain the correct response if I post the following data in Postman

x-www-form-urlencoded radio button checked

Entered the following 2 array data:
    product_id_list[]          pid1234
    product_id_list[]          pid1235

Header - Content-Type: application/x-www-form-urlencoded

Method: Post

But when I tried to do it through axios, it doesn't seems the correct params data can get through. I've tried

axios.post('https://test.com/api/get_product,
    querystring.stringify({
      'product_id_list': ['pid1234', 'pid1235']
    }))
.
.
.
axios.post('https://test.com/api/get_product,
    querystring.stringify({
      'product_id_list[]': 'pid1234',
      'product_id_list[]': 'pid1235'
    }))
.
.
.

Anyone got an idea on how to translate this type of array data in axios?

Best Answer

This issue popped up for me as well, and I solved it with new FormData().

Having an array:

const product_id_list = ['pid1234', 'pid1235']

const bodyFormData = new FormData();

product_id_list.forEach((item) => {
    bodyFormData.append('product_id_list[]', item);
});

axios.post('https://test.com/api/get_product', bodyFormData)

Doing it this way sent it the request as application/x-www-form-urlencoded, and the proper data in the body.