Code Monkey home page Code Monkey logo

Comments (8)

DigitalBrainJS avatar DigitalBrainJS commented on May 3, 2024 1

Axios v1 encodes nested objects in qs style, not as JSON string.
Unfortunately qs does not support serializing a nested object with an empty structure and there is no specification for this or well-known practice.

import qs from "qs";

const params = {
  limit: 100,
  address: { city: {} },
  details: { name: {} },
};

console.log("query:", qs.stringify(params)); // query: limit=100

However, you can use a simple interceptor to achieve your needs:

axios.interceptors.request.use((config) => {
  const { params } = config;
  if (params) {
    const _params = {};
    Object.entries(params).forEach(([key, value]) => {
      _params[key] =
        value && typeof value === "object" ? JSON.stringify(value) : value;
    });
    config.params = _params;
  }
  return config;
});

from axios.

jaymehta002 avatar jaymehta002 commented on May 3, 2024

Object-type params like address and details are not passed down to the server when sent as a plain object. However, it works fine when using URLSearchParams()
Modify the code to use URLSearchParams() for handling query parameters. This ensures proper encoding, including empty objects. Here's an example:

const params = { limit: 100, address: { city: {} }, details: { name: {} } };
const queryString = new URLSearchParams(params).toString();

axios.get(`/url?${queryString}`)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });

from axios.

jaymehta002 avatar jaymehta002 commented on May 3, 2024

or can you share the reference to the file?
i can take a second look

from axios.

ManchukondaManoj avatar ManchukondaManoj commented on May 3, 2024

Object-type params like address and details are not passed down to the server when sent as a plain object. However, it works fine when using URLSearchParams() Modify the code to use URLSearchParams() for handling query parameters. This ensures proper encoding, including empty objects. Here's an example:

const params = { limit: 100, address: { city: {} }, details: { name: {} } };
const queryString = new URLSearchParams(params).toString();

axios.get(`/url?${queryString}`)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });

These are working fine in 0.24.0 version, it is not working when upgraded to 1.6.0 & it is also not mentioned anything related in the docs.

from axios.

ManchukondaManoj avatar ManchukondaManoj commented on May 3, 2024

Thanks, Implemented similar.

if (config.params) {
        const configParams = config.params;
        delete config.params;
        const params = new URLSearchParams();
        Object.entries(configParams).forEach((param) => {
            const [key, value] = param;
            if (value !== null && value !== undefined) {
                const val = typeof value === 'object' ? JSON.stringify(value) : value;
                params.set(key, val);
            }
        });
        config.params = params;
    }

from axios.

ManchukondaManoj avatar ManchukondaManoj commented on May 3, 2024

@DigitalBrainJS facing the same issue, #5986

any alternative to the mentioned issue?

from axios.

imthematrix avatar imthematrix commented on May 3, 2024

I had the same problem and I didn't find any documentation on how the parameters were actually converted. Why does axios v1 not turn them into JSON anymore?

It converts {limit: 100, address: { city: "a" }, details: { name: "b" }} to limit=100&address[city]=a&details[name]=b now.

from axios.

imthematrix avatar imthematrix commented on May 3, 2024
axios.interceptors.request.use((config) => {
  const { params } = config;
  if (params) {
    const _params = {};
    Object.entries(params).forEach(([key, value]) => {
      _params[key] =
        value && typeof value === "object" ? JSON.stringify(value) : value;
    });
    config.params = _params;
  }
  return config;
});

Could you also use the paramsSerializer property in the config object? Why do you use an interceptor? It looks like paramsSerializer exists exactly for this purpose. But I'm not sure how it works exactly.

What's the purpose of this conditional expression value && typeof value === "object" ? JSON.stringify(value) : value? I think plain JSON.stringify(value) should work as well.

from axios.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.