NodeJs Axios响应编码错误

hs1ihplo  于 2022-11-29  发布在  Node.js
关注(0)|答案(1)|浏览(158)

我尝试使用Axios调用REST调用,但得到一个奇怪的响应。

try {
  
   const response = await axios.get("https://api.predic8.de/shop/products/");
   console.log(response.data);
}
catch (error) {
    console.log(`[Error] -> ${JSON.stringify(error.response.data)}`)
}

它会产生下列输出:
第一章:第二章:第三章:第四章:*************
我必须做什么来获得一个json对象?
我尝试使用编码和内容类型添加标头标头,但没有成功。

a8jjtwal

a8jjtwal1#

你需要在axios.get头文件中添加Accept-Encodingapplication/json
默认值为gzip
演示代码

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();

测试结果

$ 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"
        }
    ]
}

相关问题