【问题标题】:Send nested objects in GET method URL search params in Axios在 Axios 中的 GET 方法 URL 搜索参数中发送嵌套对象
【发布时间】:2019-07-25 10:11:45
【问题描述】:

我正在尝试使用如下 URL 搜索参数发送请求,但我无法访问服务器端的嵌套对象 filter

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

我可能做错了什么?
我在服务器端使用 Django restFramework 3,我无法访问该方法中的 filter 键。我正在使用request.query_params 访问查询参数,但是当我使用request.query_params.get('filter') 时,我得到none

【问题讨论】:

  • 你用什么来运行你的服务器? NodeJS 与 Express?还是……别的什么?
  • Django rest Framework 3 .... 我正在使用request.query_params 访问查询参数,但是当我使用request.query_params.get('filter') 时,我得到none

标签: reactjs get django-rest-framework axios


【解决方案1】:

您需要序列化您的参数,您可以通过编写this github issue 中提到的小配置来完成,

通常您会在 main.js 文件或应用程序的顶级文件中包含此配置,但同样取决于您希望何时执行它

// 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;
});

从 axios 0.18.0 开始:

// 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;
});

【讨论】:

  • Qsaxios 0.18.0 开始被删除。使用库 query-stringqs 为之后访问此答案的任何人编码参数。
猜你喜欢
  • 2017-06-23
  • 2020-05-21
  • 2020-08-24
  • 2018-03-20
  • 1970-01-01
  • 2020-06-11
  • 2019-08-29
  • 2021-11-29
  • 2020-06-15
相关资源
最近更新 更多