You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中如何使用axios的params发送key[op]:value格式请求参数

实现方法
  • 方法1:直接用字符串包裹带特殊符号的键
    这是最通用的方案,JS对象的键如果包含[]这类特殊字符,不能直接作为标识符书写,用单引号/双引号包裹即可正常定义,axios默认会自动对参数做URL编码,绝大多数后端框架都可以正常解析。
    代码示例:
axios.get(`http://localhost:8000/api/v1/stocks/${params.id}`, {
  params: {
    search: searchKeyword,
    // 特殊格式的键名用引号包裹
    'cost[gte]': 300
  }
})
  • 方法2:动态生成参数键
    如果操作符是动态变量,可以用计算属性拼接生成参数键:
    代码示例:
// 操作符可根据业务动态修改
const op = 'gte'
const paramsKey = `cost[${op}]`

axios.get(`http://localhost:8000/api/v1/stocks/${params.id}`, {
  params: {
    search: searchKeyword,
    [paramsKey]: 300
  }
})
  • 特殊场景:自定义参数序列化
    如果你的后端服务无法识别编码后的方括号(%5B、%5D),可以借助qs库自定义序列化规则,关闭编码:
    代码示例:
import qs from 'qs'

axios.get(`http://localhost:8000/api/v1/stocks/${params.id}`, {
  params: {
    search: searchKeyword,
    'cost[gte]': 300
  },
  paramsSerializer: params => qs.stringify(params, { encode: false })
})

内容的提问来源于stack exchange,提问作者MHS QUERIES

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:57:03