在请求中如果url包括特殊字符的话,可能会导致接口接收参数失败(例:空格 被转换成 + 号),所以前端一般会对特殊字符进行encode

encodeURI 对一个完整的URI 进行编码,
而encodeURIComponent对URI 的一个组件(单个参数)进行编码。 浏览器get请求
service.interceptors.request.use(config => {
let url = config.url
if (config.method === 'get' && config.params) {
url += '?' // 拼接参数
// 获取所有参数,通过循环 拼接所有参数,encodeURIComponent对参数编码,
Object.keys(config.params).map(key => {
url += `${key}=${encodeURIComponent(config.params[key])}&`
})
url = url.substring(0, url.length - 1) // 删除最后一个&字符
config.params = {} // 参数已经存在于 url中
}
config.url = url
return config
}
本文讲述了前端如何在发送GET请求时,通过encodeURIComponent确保特殊字符编码,避免接口接收参数错误。讲解了如何在axios拦截器中对查询参数进行编码操作。

被折叠的 条评论
为什么被折叠?



