Home > Back-end >  Axios GET returns non-readable response
Axios GET returns non-readable response

Time:11-25

I have an express app with a simple GET with axios (1.2.0):

const result: AxiosResponse = await axios.get('https://jsonplaceholder.typicode.com/posts')

The result.data ends up a cryptic, badly encoded string:

k�H���>������T��N.���r�H�v �_"9'?1���J��\���LA.  ��H���!�b�R� 9�܅��ڹ�K�}��%��A�v�Q*�g�dwf� ..goes long

I have tried with different configs added to the request but no luck. Also couldn't find any related posts elsewhere.

Why would this be? How could I fix it?

CodePudding user response:

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

The default of it is gzip

You can use 1.2 with this code

const axios = require('axios')

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

getTitles();

Result

$ node titles.js
[
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio r
eprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et
cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem
eveniet architecto"
    },
    {
        "userId": 1,
        "id": 2,
        "title": "qui est esse",
        "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor b
eatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut
 reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    },
    removed

CodePudding user response:

Edit

Tried GET using chrome dev console and the request works. Data gets decoded correctly.

resp = await fetch("https://jsonplaceholder.typicode.com/posts").then(res=> res.json())

So I guess this is an axios problem. Try using older versions.


This seems like a problem with the JsonPlaceholder API.

Axios can't decode the Json correctly probably because of some server misconfiguration regarding compression.

I tried GET with another url having the same response headers and the same compression and it worked fine.

axios.default.get("https://reddit.com/r/android.json") 
  • Related