2023.02.10 - axios发送Get请求特殊字符转码

现有一个Get请求的接口,一个字段的值传入的是ywh=[JOJO],请求报错,返回400状态码。

报错原因:URL参数格式不正确

解决方案:axios请求拦截器中对get参数进行encodeURI转码。为了避免服务器收到不可预知的请求,对任何用户输入的作为 URI 部分的内容你都需要用 encodeURIComponent 进行转义。

简便实现

// request拦截器
service.interceptors.request.use(config => {
  let url = config.url + '?';
    let keys = Object.keys(config.params);
    for (let key of keys) {
      url += `${key}=${encodeURIComponent(config.params[key])}&`;
    }
    url = url.slice(0,-1);
    config.params = {};
    config.url = url;
  return config
}

若依实现

// request拦截器
service.interceptors.request.use(config => {
  if (config.method === 'get' && config.params) {
    // 重新编码
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}
/**
* 参数处理[对象转参数 || 参数转义]
* @param {*} params  参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}
posted @ 2023-02-10 11:51  吕业浩  阅读(1216)  评论(0编辑  收藏  举报