Axios POST请求返回类似Wing Ding符号的乱码问题求助
问题:Axios POST请求返回乱码但Postman正常(状态码200)
用Postman发送POST请求能正常获取JSON格式响应,但使用Axios发送相同请求时,尽管返回200状态码,却得到一堆类似Wing Ding符号的乱码。
我的Axios代码
const configAxios = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; axios .post(url + 'connect/token', params, configAxios) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error); });
返回的乱码内容
���������⌂�N▼~����O�����ӟ�Ƀ����w~������͗{�������vwg�h~v����{/⌂zQ�^�O�=�⌂p�����_� V��O�_<]>���☼��|q��ᓋ��Y�����ߙ�8}����]����^�^���}^���ç�W_�{��էg�Κ�>ث▬?�����^��N�^����I���D�;����I5����⌂�t6�>x��↨U��‼m����d{y���⌂�������~ж_�>;/�/>⌂�{7�v�[⌂�ݫ����>�����f�s���>,�]}4�(⌂�*���♂��{���>b�����UN|�$�꼦vʹ�☼�>}v�*~�Wy6���?��§('♥
Postman预期返回结果
{ "access_token": "{access_token}", "expires_in": 3600, "token_type": "Bearer", "scope": "api_read" }
解决办法
1. 处理Gzip压缩响应
多数API会返回Gzip压缩内容,Postman自动解压,但Axios默认可能未开启该功能。添加请求头并强制解析为JSON:
const configAxios = { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept-Encoding': 'gzip, deflate' }, responseType: 'json' };
Node.js环境需额外引入zlib模块处理解压,浏览器环境通常无需额外配置。
2. 修正参数序列化
确保请求参数被正确序列化为application/x-www-form-urlencoded格式,使用qs库手动处理:
import qs from 'qs'; // 先执行 npm install qs 安装 const configAxios = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; axios.post(url + 'connect/token', qs.stringify(params), configAxios) .then(res => console.log(res.data)) .catch(err => console.log(err));
3. 手动指定字符编码
如果服务器返回非UTF-8编码内容,需手动解码:
- 浏览器环境用
TextDecoder:
const configAxios = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformResponse: [data => new TextDecoder('gbk').decode(data)] // 替换为实际编码 };
- Node.js环境用
iconv-lite库:
const iconv = require('iconv-lite'); const configAxios = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, responseType: 'arraybuffer', transformResponse: [data => iconv.decode(data, 'gbk')] // 替换为实际编码 };
内容的提问来源于stack exchange,提问作者Acer79
相关产品推荐
相关产品推荐

