Axios 返回奇怪的垃圾值,例如
�2���ϫ�M@�~�II�{!
我在 wsl2 ubuntu 上, Node 版本是 v19.0,axios 是 1.2.0
我的代码再简单不过了: `
const axios = require("axios");
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => console.log(response.data))
fetch() 工作得很好。有什么想法或可能的解决方案吗?
最佳答案
在 v1.2.1 中修复了这个错误。
您需要在 v1.2.0 的 axios.get header 中添加 Accept-Encoding
和 application/json
默认为gzip
这是v1.2.0中的演示代码
const axios = require("axios");
const getUsers = async () => {
try {
const resp = await axios.get('https://jsonplaceholder.typicode.com/users',
{
headers: {
'Accept-Encoding': 'application/json',
}
}
);
console.log(JSON.stringify(resp.data, null, 4));
} catch (err) {
// Handle Error Here
console.error(err);
}
};
getUsers();
或者你的代码风格。
const axios = require("axios");
axios.get('https://jsonplaceholder.typicode.com/users',
{
headers: {
'Accept-Encoding': 'application/json',
}
})
.then(response => console.log(response.data))
结果
$ node test.js
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
... removed
关于javascript - Axios 返回垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74578713/