如何在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
相关产品推荐
相关产品推荐

