axios get请求传参数实战指南:从基础用法到高级配置

1次阅读
没有评论

共计 1909 个字符,预计需要花费 5 分钟才能阅读完成。

image.webp

核心概念:URL 参数与 axios 处理机制

URL 参数(Query String)是 GET 请求中传递数据的标准方式,格式为 ?key1=value1&key2=value2。axios 内部会自动将params 对象转换为这种格式,并处理以下关键细节:

axios get 请求传参数实战指南:从基础用法到高级配置

  • 参数编码:自动对特殊字符(如空格、中文)进行 URL 编码
  • 数组处理:默认转换为 key[]=value1&key[]=value2 格式
  • 空值过滤:可通过配置决定是否保留 null/undefined

新手常见痛点

  1. 参数丢失 :未正确使用params 对象导致参数未附加到 URL
  2. 特殊字符报错 :未编码的&# 等字符破坏 URL 结构
  3. 数组格式混乱:服务端无法解析自行拼接的数组参数
  4. 布尔值问题 false 值被错误过滤

技术方案详解

基础用法:URL 拼接(不推荐)

// 手动拼接存在编码风险
axios.get('/api?name= 张三 &age=25')

推荐方式:params 对象

axios.get('/api', {
  params: {
    name: '张三',
    age: 25,
    tags: ['vue', 'react'],  // 自动处理为 tags[]=vue&tags[]=react
    emptyParam: null         // 默认会被过滤
  }
})

高级配置方案

方案 1:URLSearchParams

const params = new URLSearchParams()
params.append('name', '李四')
params.append('search', 'vue&react') // 自动编码

axios.get('/api', { params})

方案 2:axios 全局配置

// 设置全局 params 处理规则
axios.defaults.paramsSerializer = {encode: (val) => encodeURIComponent(val),
  serialize: (params) => {// 自定义序列化逻辑}
}

完整示例代码

import axios from 'axios';

// 带错误处理的请求示例
const fetchUser = async (userId, filters) => {
  try {
    const response = await axios.get('/api/users', {
      params: {
        id: userId,
        ...filters,
        // 显式控制空值行为
        showInactive: filters.inactive || undefined 
      },
      // 超时和重试配置
      timeout: 5000,
      retry: 2 
    });
    return response.data;
  } catch (error) {if (error.response) {
      // 服务端返回 4xx/5xx 错误
      console.log('Server responded with:', error.response.status);
    } else if (error.request) {
      // 请求已发出但无响应
      console.log('No response received');
    } else {
      // 请求配置错误
      console.log('Request setup error:', error.message);
    }
    throw error;
  }
};

避坑指南

  1. 编码最佳实践
  2. 永远不要手动拼接 URL
  3. 复杂参数使用URLSearchParams
  4. 服务端需要原始字符时使用encodeURIComponent

  5. 空值处理方案

    params: {
      // 使用 undefined 而非 null 更安全
      optionalParam: shouldInclude ? value : undefined
    }

  6. 数组 / 对象参数

  7. 默认格式:arr[]=1&arr[]=2
  8. 需要其他格式时自定义paramsSerializer

拦截器中的高级处理

// 请求拦截器统一添加参数
axios.interceptors.request.use(config => {if (config.method === 'get') {
    config.params = {
      ...config.params,
      timestamp: Date.now(), // 防止缓存
      apiVersion: '1.0'
    };
  }
  return config;
});

性能优化建议

  1. 对于高频请求,考虑合并参数减少 URL 长度
  2. 大量参数时建议改用 POST+ 请求体
  3. 启用 keep-alive 复用连接

思考题

  1. 当需要向后端传递多层嵌套对象时,有哪些参数序列化方案?
  2. 如何设计一个拦截器,实现对特定参数的自动加密?
  3. 在微前端架构中,如何避免各子应用的 axios 实例参数配置冲突?

通过本文的实践方案,你应该能解决 95% 的 axios GET 传参问题。记住核心原则:永远让 axios 处理参数编码和序列化,避免手动操作 URL 字符串。

正文完
 0
评论(没有评论)