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

如何在axios post请求中移除JSON内的反斜杠(replace方法无效)

问题描述

发送axios post请求时,提交的JSON内容会自动被添加反斜杠,即便使用replace方法做了处理,反斜杠依然没有被成功移除。

问题代码

axios
      .post(
        "https://test-manager/backend",
        {
          gameName: this.gameName,
          platform: this.gamePlatform,
          json: finalData.replace(/\\/g, ""),
        }
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

问题现象

问题现象截图

根因说明

多余反斜杠的本质是重复JSON序列化:
如果你的finalData本身已经是调用JSON.stringify()生成的JSON字符串,将它放入请求参数对象后,axios默认会对整个POST请求体自动执行一次JSON序列化操作,finalData字符串里的引号等特殊字符会被二次转义,就产生了多余的反斜杠。
你提前执行的replace(/\\/g, "")操作是在axios自动序列化之前运行的,序列化时反斜杠会被重新生成,所以该处理无效。

解决方案

根据后端接口的字段要求选择对应处理方式:

  • 若后端要求json字段接收JSON对象:直接传入finalData对应的原始JS对象即可,不要提前转成字符串,也不需要做替换处理
    axios
      .post(
        "https://test-manager/backend",
        {
          gameName: this.gameName,
          platform: this.gamePlatform,
          json: finalData
        }
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
  • 若后端要求json字段接收JSON格式的字符串:先将已经序列化的finalData转回JS对象再传入,axios整体序列化请求体时就不会生成多余的转义字符
    axios
      .post(
        "https://test-manager/backend",
        {
          gameName: this.gameName,
          platform: this.gamePlatform,
          json: JSON.parse(finalData)
        }
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

内容的提问来源于stack exchange,提问作者Ömür Özbek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:06:02