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 解码

相关推荐
fruge1 小时前
Vue项目中的Electron桌面应用开发实践指南
前端·vue.js·electron
漂流瓶jz7 小时前
Webpack中各种devtool配置的含义与SourceMap生成逻辑
前端·javascript·webpack
这是个栗子7 小时前
【问题解决】用pnpm创建的 Vue3项目找不到 .eslintrc.js文件 及 后续的eslint配置的解决办法
javascript·vue.js·pnpm·eslint
前端架构师-老李7 小时前
React 中 useCallback 的基本使用和原理解析
前端·react.js·前端框架
木易 士心8 小时前
CSS 中 `data-status` 的使用详解
前端·css
明月与玄武8 小时前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
牧马少女8 小时前
css 画一个圆角渐变色边框
前端·css
zy happy8 小时前
RuoyiApp 在vuex,state存储nickname vue2
前端·javascript·小程序·uni-app·vue·ruoyi
小雨青年9 小时前
Cursor 项目实战:AI播客策划助手(二)—— 多轮交互打磨播客文案的技术实现与实践
前端·人工智能·状态模式·交互
Nan_Shu_6149 小时前
学习:JavaScript(5)
开发语言·javascript·学习