浙江省建设网站,网站优化内容原创,wordpress 3.5 基础教程,图书馆网站建设总结1、axios调接口特殊字符丢失的问题
项目开发过程中遇到一个接口传参#xff0c;参数带特殊字符#xff0c;axios调接口特殊字符丢失的问题
例如接口#xff1a; get/user/detail/{name} name是个参数直接调接口的时候拼到接口上#xff0c;get/user/detail/test123#$%参数带特殊字符axios调接口特殊字符丢失的问题
例如接口 get/user/detail/{name} name是个参数直接调接口的时候拼到接口上get/user/detail/test123#$%调接口发现后面的特殊字符#$%丢失了调的接口变成了get/user/detail/test123
2、解决办法
参数使用encodeURIComponent编译一下再拼到接口上这样特殊字符不会丢失后端可以正常接收参数。
import Axios from src/axios/index.js;const name test123#$%;// 直接拼接口上
Axios.get(get/user/detail/${name}).then(function (response) {console.log(response);
}).catch(function (error) {console.log(error);
});// 参数使用encodeURIComponent编译一下,再拼接口上
Axios.get(get/user/detail/${encodeURIComponent(name)}).then(function (response) {console.log(response);
}).catch(function (error) {console.log(error);
});
// 直接拼接口上 // 参数使用encodeURIComponent编译一下,再拼接口上 3、延伸
使用params传参如果直接将参数使用拼接到后面也是会存在特殊字符丢失的问题
import Axios from src/axios/index.js;
const name test123#$%;// 直接拼接口上
Axios({url: get/user/detail?name${name},method: get,
}).then(function (response) {console.log(response);
}).catch(function (error) {console.log(error);
});// 参数使用encodeURIComponent编译一下,再拼接口上
Axios({url: get/user/detail?name${encodeURIComponent(name)},method: get,
}).then(function (response) {console.log(response);
}).catch(function (error) {console.log(error);
});// 正常逻辑传参数推荐
Axios({url: get/user/detail,method: get,params: { name },
}).then(function (response) {console.log(response);
}).catch(function (error) {console.log(error);
});
// 直接拼接口上 // 参数使用encodeURIComponent编译一下,再拼接口上 // 正常逻辑传参数推荐 4、encodeURI 和 encodeURIComponent
MDN上关于encodeURI 和 encodeURIComponent的介绍
encodeURI() - JavaScript | MDN
encodeURIComponent() - JavaScript | MDN encodeURIComponent不转义的字符包括
类型包含非转义的字符字母 数字 - _ . ! ~ * ( )
encodeURI不转义的字符包括
类型包含保留字符; , / ? : $非转义的字符字母 数字 - _ . ! ~ * ( )数字符号#
5、解码
encodeURI使用decodeURI解码encodeURIComponent使用decodeURIComponent 解码