共计 1909 个字符,预计需要花费 5 分钟才能阅读完成。
核心概念:URL 参数与 axios 处理机制
URL 参数(Query String)是 GET 请求中传递数据的标准方式,格式为 ?key1=value1&key2=value2。axios 内部会自动将params 对象转换为这种格式,并处理以下关键细节:

- 参数编码:自动对特殊字符(如空格、中文)进行 URL 编码
- 数组处理:默认转换为
key[]=value1&key[]=value2格式 - 空值过滤:可通过配置决定是否保留
null/undefined值
新手常见痛点
- 参数丢失 :未正确使用
params对象导致参数未附加到 URL - 特殊字符报错 :未编码的
&、#等字符破坏 URL 结构 - 数组格式混乱:服务端无法解析自行拼接的数组参数
- 布尔值问题 :
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;
}
};
避坑指南
- 编码最佳实践
- 永远不要手动拼接 URL
- 复杂参数使用
URLSearchParams -
服务端需要原始字符时使用
encodeURIComponent -
空值处理方案
params: { // 使用 undefined 而非 null 更安全 optionalParam: shouldInclude ? value : undefined } -
数组 / 对象参数
- 默认格式:
arr[]=1&arr[]=2 - 需要其他格式时自定义
paramsSerializer
拦截器中的高级处理
// 请求拦截器统一添加参数
axios.interceptors.request.use(config => {if (config.method === 'get') {
config.params = {
...config.params,
timestamp: Date.now(), // 防止缓存
apiVersion: '1.0'
};
}
return config;
});
性能优化建议
- 对于高频请求,考虑合并参数减少 URL 长度
- 大量参数时建议改用 POST+ 请求体
- 启用
keep-alive复用连接
思考题
- 当需要向后端传递多层嵌套对象时,有哪些参数序列化方案?
- 如何设计一个拦截器,实现对特定参数的自动加密?
- 在微前端架构中,如何避免各子应用的 axios 实例参数配置冲突?
通过本文的实践方案,你应该能解决 95% 的 axios GET 传参问题。记住核心原则:永远让 axios 处理参数编码和序列化,避免手动操作 URL 字符串。
正文完
发表至: 前端开发
近一天内
