2

data example we want to send by ajax

const dataExample = {
    "userId": '...id',
    "supportFormId": 14,
    "supportFormName": 'Tickets',
    "customFields": [
        {
            "customFieldId": 80,
            "name": 'Subject',
            "value": '...',
            "dataType": 'Text'
        },
        // ....
        {
            "customFieldId": 84,
            "name": 'Description',
            "value": '...',
            "dataType": 'Text'
        }
    ]
}

jQuery ajax call


$.ajax({
    type: 'post',
    url: 'http://....',
    dataType: 'json',
    data: dataExample,
    success: function (data) { /* ... */ }
});

axios + query-string ajax call


import axios from "axios";
import qs from 'query-string'

const dataQs = qs.stringify(dataExample);

return new Promise(
    async (resolve, reject) => {
        try {
            const response = await axios({
                method: 'post',
                headers: { 'content-type': 'application/x-www-form-urlencoded' },
                data: dataQs,
                url: 'http://....'
            });
            if (response) return resolve(response)
            return reject()
        } catch (err) { return reject(err) }
    }
);

result

result

question

jQuery never has any type of problem but axios + query-string, despite different headers like

'content-type': 'application/json',
'content-type': 'multipart/form-data',

and/or optional stringify options like

const dataQs = qs.stringify(data, { encode: false })
const dataQs = qs.stringify(data, { arrayFormat: 'indices', commaSuffix: 'bracket' })
const dataQs = qs.stringify(data, { arrayFormat: 'indices' })
const dataQs = qs.stringify(data, { arrayFormat: 'brackets' })
const dataQs = qs.stringify(data, { arrayFormat: 'repeat' })
const dataQs = qs.stringify(data, { arrayFormat: 'comma' })

breaks the data all the times..

which is the correct axios + query-string (or alternative) code to get the same result of jQuery?

1
  • You send json formatted data with jQuery and url/parameter (query-string) encoded data with axios. As you use query-string, it is always url-encoded with axios; no matter what header (content-Type) you use. Perhaps the server can only handle json data, so it works with jQuery and fails with axios. Have you access to and looked into the server logs? You could format the data string with JSON.stringify and use Content-Type: application/json to try. Just a guess. Commented Jan 20, 2021 at 11:40

1 Answer 1

3
+50

You can use something like below

const objectToQueryString = (initialObj) => {
    const reducer = (obj, parentPrefix = null) => (prev, key) => {
      const val = obj[key];
      key = encodeURIComponent(key);
      const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;

      if (val == null || typeof val === 'function') {
        prev.push(`${prefix}=`);
        return prev;
      }

      if (['number', 'boolean', 'string'].includes(typeof val)) {
        prev.push(`${prefix}=${encodeURIComponent(val)}`);
        return prev;
      }

      prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
      return prev;
    };

    return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
  };

  objectToQueryString({
    name: 'John Doe',
    age: 20,
    children: [
      { name: 'Foo Doe' },
      { name: 'Bar Doe' }
    ],
    wife: {
      name: 'Jane Doe'
    }
  });
  // -> name=John%20Doe&age=20&children[0][name]=Foo%20Doe&children[1][name]=Bar%20Doe&wife[name]=Jane%20Doe

Taken from below gist

https://gist.github.com/tjmehta/9204891

Sign up to request clarification or add additional context in comments.

1 Comment

this is the solution I was looking for!!! thank you very much, it works!!! you will get 50+ in 23 hours :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.