You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Axios URL中传递|符号?请求时符号被转义为%7C的解决方法

如何在Axios的URL中保留|符号不被转义

遇到这种情况很常见——Axios默认会按照URL规范对特殊字符进行编码,|属于需要转义的字符,所以自动变成了%7C。如果后端明确要求必须传递原始的|符号,你可以试试下面几种解决方案:

1. 自定义参数序列化规则(推荐)

Axios默认使用qs库处理参数序列化,你可以通过paramsSerializer配置项自定义编码逻辑,让|符号保留原样。

方法A:手动实现序列化

如果不想额外引入库,可以自己写简单的序列化函数:

import axios from 'axios';

const axiosInstance = axios.create({
  paramsSerializer: {
    encode: (params) => {
      return Object.entries(params)
        .map(([key, value]) => {
          // 编码参数名,保留参数值中的|
          const encodedKey = encodeURIComponent(key);
          const preservedValue = value.toString().replace(/%7C/g, '|');
          return `${encodedKey}=${preservedValue}`;
        })
        .join('&');
    }
  }
});

// 使用实例发起请求
axiosInstance.get('https://xxxxxxxxxxx.com/HiThere', {
  params: {
    fullName: `${firstName}|${lastName}`
  }
});

方法B:借助qs库自定义编码器

如果你已经在项目中使用qs,可以更灵活地配置:

import axios from 'axios';
import qs from 'qs';

const axiosInstance = axios.create({
  paramsSerializer: (params) => {
    return qs.stringify(params, {
      encoder: (str) => {
        // 对字符串编码后,把转义后的%7C替换回|
        return encodeURIComponent(str).replace(/%7C/g, '|');
      }
    });
  }
});

2. 直接处理完整URL(路径中的|)

如果|是在URL路径部分(而非查询参数),比如你直接拼接的/HiThere/${firstName}|${lastName},可以先构建原始URL,再通过decodeURIComponent让Axios最终发送的URL保留|:

const firstName = 'John';
const lastName = 'Doe';
const rawUrl = `https://xxxxxxxxxxx.com/HiThere/${firstName}|${lastName}`;

axios.get(decodeURIComponent(rawUrl))
  .then(res => console.log(res))
  .catch(err => console.error(err));

⚠️ 注意:这种方式要确保firstName和lastName中不包含其他需要编码的特殊字符,否则可能导致URL格式错误或安全问题。

额外提醒

按照URL标准,|确实属于需要编码的字符,所以建议先确认后端是否真的不能接受%7C——如果后端可以兼容编码后的字符,那最好保留默认的编码行为,这样更符合规范。

内容的提问来源于stack exchange,提问作者Ajay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:36:35