axios调接口传参特殊字符丢失的问题(encodeURI 和 encodeURIComponent)

1、axios调接口特殊字符丢失的问题

项目开发过程中遇到一个接口传参,参数带特殊字符,axios调接口特殊字符丢失的问题

例如接口:

get/user/detail/{name}

name是个参数直接调接口的时候拼到接口上,get/user/detail/test123#%,调接口发现后面的特殊字符#%丢失了,调的接口变成了get/user/detail/test123

2、解决办法:

参数使用encodeURIComponent编译一下,再拼到接口上,这样特殊字符不会丢失,后端可以正常接收参数。

javascript 复制代码
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传参,如果直接将参数使用?拼接到后面,也是会存在特殊字符丢失的问题

javascript 复制代码
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 解码

相关推荐
JefferyXZF15 分钟前
Next.js 路由导航:四种方式构建流畅的页面跳转(三)
前端·全栈·next.js
啃火龙果的兔子27 分钟前
React 多语言(i18n)方案全面指南
前端·react.js·前端框架
阿奇__1 小时前
深度修改elementUI样式思路
前端·vue.js·elementui
小白白一枚1111 小时前
css的选择器
前端·css
盛夏绽放1 小时前
SassSCSS:让CSS拥有超能力的预处理器
前端·css·rust
xw52 小时前
支付宝小程序IDE突然极不稳定
前端·支付宝
Dolphin_海豚3 小时前
vapor 语法糖是如何被解析的
前端·源码·vapor
Bdygsl4 小时前
前端开发:HTML(5)—— 表单
前端·html
望获linux4 小时前
【实时Linux实战系列】实时数据流处理框架分析
linux·运维·前端·数据库·chrome·操作系统·wpf
red润4 小时前
let obj = { foo: 1 };为什么Reflect.get(obj, ‘foo‘, { foo: 2 }); // 输出 1?
开发语言·javascript·ecmascript