skip to Main Content

I recently tried to fix all npm vulnerabilities in a project. Part of that attempt was upgrading Axios from 0.27.2 to 1.6.2.

In doing so, the format of the params prop for axios.get requests was changed. It was changed from something like:

enter image description here

To something like:

enter image description here

Source: https://github.com/axios/axios/issues/4999

How can I upgrade Axios but still use the same format as before?

I tried adding the following to my Axios instance, but it doesn’t seem to work:

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    It turns out Axios in 1.6.2 was sending the data fine to the server for get requests. My problem is that I was assuming I had to decode (parse) JSON data when objects or arrays of data were being sent for subprops of params.

    After removing that assumption in my back-end code, everything worked.


  2. Use this

    axios.defaults.paramsSerializer = params =>
      Object.keys(params)
        .filter(key => params[key] !== undefined)
        .map(key => {
          if (Object.prototype.toString.call(params[key]) === "[object Object]") {
            params[key] = JSON.stringify(params[key]);
          }
          if (Array.isArray(params[key])) {
            return params[key].map((v: any) => `${key}[]=${encodeURIComponent(v)}`).join("&");
          }
          return `${key}=${encodeURIComponent(params[key])}`;
        })
        .join("&");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search