Home > Mobile >  Axios returning garbage values
Axios returning garbage values

Time:11-27

Axios is returning weird garbage values, such as �2���ϫ��M@�~�II�{!

I'm on a wsl2 ubuntu, node-version is v19.0, axios is 1.2.0

My code could not be easier: `

const axios = require("axios");

axios.get('https://jsonplaceholder.typicode.com/users')
    .then(response => console.log(response.data))

fetch() is working like a charm. Any ideas or possible solutions?

CodePudding user response:

You need to add Accept-Encoding with application/json in axios.get header.

The default of it is gzip

This is demo code

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

Or your code style.

const axios = require("axios");

axios.get('https://jsonplaceholder.typicode.com/users',
    {
        headers: {
            'Accept-Encoding': 'application/json',
        }
    })
    .then(response => console.log(response.data))

Result

$ node test.js
[
    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "[email protected]",
        "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
  • Related