Axios发起简单API GET请求时response.data返回乱码求助
Axios请求返回response.data乱码问题解决
问题描述
我编写了一个测试函数试用Axios,但返回的response.data对象出现乱码。谷歌搜索未找到有效解决方法,且我的代码写法与Axios教程完全一致。
请求代码:
var axios = require('axios'); const getCatFact = async () => { const url = "https://catfact.ninja/fact"; const response = await axios.request({ method: 'GET', url: url, }); console.log(response.data); }; getCatFact();
返回乱码结果:
%O�j�@ ��aO-����������{�nٕ������a4��0J��>���+�,D�ˢ �bV�G��/I�Cw�Rf¤L���Z�5w����]ӄ���s������ I.b�z"�IR��M����(N3��Y���귴���m�ۤ� ��Xuz���t�uS�y\��5=61������4y �����!{��
已尝试的操作:
- 在Chrome中访问该URL,通过Postman发起GET请求,确认API本身无问题
- 使用另一个API(
https://jsonplaceholder.typicode.com/posts/1)测试,仍出现相同乱码问题
预期返回格式:
{"fact":"Julius Ceasar, Henri II, Charles XI, and Napoleon were all afraid of cats.","length":74}
解决方案
1. 强制指定响应类型与编码
在请求配置中添加responseType和responseEncoding参数,强制Axios以UTF-8编码解析JSON响应:
var axios = require('axios'); const getCatFact = async () => { const url = "https://catfact.ninja/fact"; const response = await axios.request({ method: 'GET', url: url, responseType: 'json', responseEncoding: 'utf8' }); console.log(response.data); }; getCatFact();
2. 重新安装Axios
可能是Axios安装文件损坏导致的问题,执行以下命令重新安装:
npm uninstall axios && npm install axios
3. 升级Node.js版本
部分旧版Node.js与Axios存在兼容性问题,建议升级到LTS稳定版本,避免编码解析异常。
内容的提问来源于stack exchange,提问作者thrillifying
相关产品推荐
相关产品推荐

