axios使用sm2加密数据后请求参数多了双引号解决方法

发布于:2024-07-11 ⋅ 阅读:(88) ⋅ 点赞:(0)

axios使用sm2加密数据后请求参数多了双引号解决

背景

因项目安全要求,需对传给后端的入参加密,将请求参数加密后再传给后端
前期将axios降低到1.6.7后解决了问题,但最近axios有漏洞,安全要求对版本升级,问题需要继续解决。
果然,技术栈不解决迟早会有问题。。。

问题描述

升到稳定版本后,在浏览器网络请求参数上发现加密后的参数加上了双引号
在这里插入图片描述
后端的日志也能看出来多了双引号,导致后端解密失败
在这里插入图片描述

正常的请求参数是不带双引号的
在这里插入图片描述

解决过程

  1. 一开始想将content-type转为text传给后端,但是此路不通,会导致后端无法接收参数,只能传json格式
Content-Type: application/json
  1. 那就转换思路,看axios是在什么地方将字符串添加了双引号的,于是在github上找到下面代码,解决问题
    代码段来自于别人的提交记录,亲测有效
const instance = axios.create({
    transformRequest: function transformRequest(data, headers) {
      // doesn't apply the default transformRequest if the data is a string, so that axios doesn't add quotes see :
      // https://github.com/usebruno/bruno/issues/2043
      // https://github.com/axios/axios/issues/4034
      const hasJSONContentType = () => {
        const contentType = (headers && headers['Content-Type']) || '';
        return contentType.indexOf('application/json') > -1;
      };
      if (typeof data === 'string' && hasJSONContentType()) {
        return data;
      }

      axios.defaults.transformRequest.forEach((tr) => tr(data, headers));
    }
  });

相关细节可查看
https://github.com/axios/axios/issues/4034
https://github.com/usebruno/bruno/pull/2449