当前位置: 首页 > article >正文

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

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

项目开发过程中遇到一个接口传参,参数带特殊字符,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 解码
 


http://www.kler.cn/news/161977.html

相关文章:

  • 【学习笔记】python仅拷贝list的值,引出浅拷贝与深拷贝
  • 在Python中,*f和**f是用于解包参数的语法
  • linux安装mysql5.7(一遍过)
  • 案例060:基于微信小程序考试系统
  • Java 简易版 UDP 多人聊天室
  • ThinkPHP插件开发实例
  • vue 使用 h函数
  • 区块链optimism主网节点搭建
  • 2024年值得关注的8个未来数据库
  • 什么是https 加密协议?
  • Javaweb之Maven仓库的详细解析
  • RPC 集群,gRPC 广播和组播
  • ELK架构监控MySQL慢日志
  • git-vscode
  • ubuntu20.04设置开机自启动jar(依赖其他服务)
  • 简单介绍一些其他的树
  • 阿里云 ACR 制品中心 AI/大数据镜像专场上新推荐榜
  • 【教程】逻辑回归怎么做多分类
  • 转转闲鱼链接后台搭建教程+完整版源码
  • 上海市青少年算法2022年10月月赛(乙组)
  • 【BUG】SpringBoot项目Long类型数据返回前端精度丢失问题
  • 论文分享 | 基于机载单目视觉的四旋翼无人机群内相对定位
  • 数据库管理-第120期 初探Halo数据库(202301201)
  • vue的props
  • git 本地有改动,远程也有改动,且文件是自动生成的配置文件
  • 【vuex】
  • 探索Vue小程序框架的底层原理
  • WPF Mvvm模式下面如何将事件映射到ViewModel层
  • lambda技巧之—如何在有多个判断分支的情况下,还能优雅的使用auto ?
  • Gee教程5.中间件