Cla*_*eld 5 javascript node.js axios
我正在尝试使用 Axios 调用 REST 调用并得到奇怪的响应。
\ntry {\n \n const response = await axios.get("https://api.predic8.de/shop/products/");\n console.log(response.data);\n}\ncatch (error) {\n console.log(`[Error] -> ${JSON.stringify(error.response.data)}`)\n}\nRun Code Online (Sandbox Code Playgroud)\n其结果如下:
\n\xe2\x96\xbc\xe2\x99\xa5\xef\xbf\xbd\xef\xbf\xbdM\n\xef\xbf\xbd0\n5\xef\xbf\xbdZ\xef\xbf\xbdz\xef\xbf \xbdwg\xef\xbf\xbd4\xd3\x8e\xef\xbf\xbdW\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdYjxt\xca \xb8\xef\xbf\xbd\xef\xbf\xbd:\xef\xbf\xbd\xc7\x8f\xe2\x96\xba_\xef\xbf\xbd\xe2\x98\xba}Y\xef\xbf\ xbd\xef\xbf\xbd/\xef\xbf\xbdR2~\xe2\x99\xa0$\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdU\xcc\x81\xef\xbf\xbdV \xef\xbf\xbd8\\\xef\xbf\xbd]!\xef\xbf\xbd )\xe2\x98\xba*\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdH\xef\xbf\xbd\xef\xbf\xbd>\xef\xbf\xbd\xc2\xa7\xef\xbf\xbd\xef\xbf\xbdAj"\xe2\x86\x95\xef\xbf\xbd\xef\xbf\xbda0 \xdd\x9a\xef\xbf\xbd\xef\xbf\xbd$\xef\xbf\xbd\xe9\xa2\xb2Y3%je3@=\xef\xbf\xbd0\xef\xbf\xbd\xef\xbf\xbd@\xc2\xa7lb:\xef\xbf\xbd|\xef\xbf\xbd} .\xe2\x98\xba8\xef\xbf\xbdK&\xef\xbf\xbd_\xc6\xabp\xef\xbf\ xbdj\xef\xbf\xbd(o-\xef\xbf\xbd\xdc\x9a\xe2\x99\xa6
我需要做什么才能获取 json 对象?
\n我尝试添加带有编码和内容类型的标头标头,但没有成功。
\n您需要在 axios.get 标头中添加Accept-Encodingwith application/json。
gzipv1.2.0 中默认是axios 在 v1.2.1 中修复了这个缺陷
v 1.2.0 中的演示代码
const axios = require('axios')
const getProducts = async () => {
try {
const resp = await axios.get(
'https://api.predic8.de/shop/products/',
{
headers: {
'Accept-Encoding': 'application/json',
}
}
);
console.log(JSON.stringify(resp.data, null, 4));
} catch (err) {
// Handle Error Here
console.error(err);
}
};
getProducts();
Run Code Online (Sandbox Code Playgroud)
OR 在 v1.2.1 中修复
const axios = require('axios')
const getProducts = async () => {
try {
const resp = await axios.get(
'https://api.predic8.de/shop/products/'
);
console.log(JSON.stringify(resp.data, null, 4));
} catch (err) {
// Handle Error Here
console.error(err);
}
};
getProducts();
Run Code Online (Sandbox Code Playgroud)
结果
$ node product.js
{
"meta": {
"count": 32,
"limit": 10,
"page": 1,
"next_url": "/shop/products/?page=2&limit=10"
},
"products": [
{
"name": "Bananas",
"product_url": "/shop/products/3"
},
{
"name": "Oranges",
"product_url": "/shop/products/10"
},
{
"name": "Pineapples",
"product_url": "/shop/products/33"
},
{
"name": "Dried Pineapples",
"product_url": "/shop/products/42"
},
{
"name": "Cranberries",
"product_url": "/shop/products/57"
},
{
"name": "Mango fresh",
"product_url": "/shop/products/62"
},
{
"name": "Raspberries",
"product_url": "/shop/products/90"
},
{
"name": "Cherries",
"product_url": "/shop/products/7"
},
{
"name": "Apple",
"product_url": "/shop/products/18"
},
{
"name": "Green Grapes",
"product_url": "/shop/products/11"
}
]
}
Run Code Online (Sandbox Code Playgroud)