11

I am trying to send the request with URL search params as below but I am not able to access a nested object filter on the server side.

axios.get('/get handler', {
  params: { 
    room: 1,
    filter: {
     fan: 2, 
     table: 1,
  }
});

What Am I possibly doing wrong?
I am using Django restFramework 3 on the server side and I am not able to access filter key in the method. I am accessing query params using request.query_params but when i do request.query_params.get('filter') I get none

2
  • What are you using to run your server? NodeJS with Express? Or... something else? Commented Mar 4, 2019 at 7:06
  • Django rest Framework 3.... I am accessing query params using request.query_params but when i do request.query_params.get('filter') I get none Commented Mar 4, 2019 at 7:08

1 Answer 1

18

You need to serialize your params and that you can do by writing a small config as mentioned in this github issue,

Usually you would have this config in the main.js file or the top level file of your application, but again it depends on when you want to execute it

// main.js
import axios from "axios";

// Format nested params correctly
axios.interceptors.request.use(config => {
  window.console.log(config);

  config.paramsSerializer = params => {
    // Qs is already included in the Axios package
    return Qs.stringify(params, {
      arrayFormat: "brackets",
      encode: false
    });
  };

  return config;
});

From axios 0.18.0 onwards:

// main.js
import axios from "axios";
import Qs from 'qs';

// Format nested params correctly
axios.interceptors.request.use(config => {

  config.paramsSerializer = params => {
    // Qs is not included in the Axios package
    return Qs.stringify(params, {
      arrayFormat: "brackets",
      encode: false
    });
  };

  return config;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Qs is removed from the axios 0.18.0 onwards. Use library query-string or qs to encode params for anyone who is visiting this answer afterwards.

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.