Home > Software engineering >  Axios response doesn't show the data
Axios response doesn't show the data

Time:11-25

I'm learning to use Axios but the output look like in the picturn ,

when i use fetch the output is normally.

how can i fix Axios ?

const axios = require("axios").default;
const url = "https://jsonplaceholder.typicode.com/users";
const timer = () => {
  axios
    .get(url)
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    });
};
timer();

Error Picture 1 Error Picturn 2

I tries to use catch but didn't show anything error

CodePudding user response:

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

The default of axios is gzip

Using this code

const axios = require("axios");
const url = "https://jsonplaceholder.typicode.com/users";
const timer = async () => {
    try {
        const resp = await axios.get(
            url,
            {
                headers: {
                    'Accept-Encoding': 'application/json',
                }
            }
        );
        console.log(JSON.stringify(resp.data, null, 4));
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
};
timer();

Result

$ node timer.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