在 Axios 中的 GET 方法 URL 搜索参数中发送嵌套对象 [英] Send nested objects in GET method URL search params in Axios

查看:45
本文介绍了在 Axios 中的 GET 方法 URL 搜索参数中发送嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

你需要序列化你的参数,你可以通过编写一个小配置来完成,如 这个 github 问题

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

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

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

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

这篇关于在 Axios 中的 GET 方法 URL 搜索参数中发送嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆