NodeJS Axios response.data对象在简单API GET请求时返回垃圾

vc9ivgsu  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(86)

I wrote a quick test function to try out Axios, and the response.data object that gets returns is garbled. I'm not sure what I'm doing wrong— I've tried Googling around for this to no avail, and all of the Axios tutorials I've found seem to be doing exactly what I'm doing.
Here's the GET request I make:

var axios = require('axios');
const getCatFact = async () => {
  const url = "https://catfact.ninja/fact";

  const response = await axios.request({
    method: 'GET',
    url: url,
  });
  console.log(response.data);
};

getCatFact();

And here's what the responses look like:

%O�j�@
      ��aO-����������{�nٕ������a4��0J��>���+�,D�ˢ
                                                �bV�G��/I�Cw�Rf¤L���Z�5w����]ӄ���s������
I.b�z"�IR��M����(N3��Y���귴���m�ۤ�   ��Xuz���t�uS�y\��5=61������4y
                                                                 �����!{��

I've tried:

  • Loading the URL in Chrome and making the GET request via Postman to validate that the API itself is not the problem.
  • Testing with a different API ( https://jsonplaceholder.typicode.com/posts/1 ), which has the same issue.

I'm expecting the snippet above to return a response that looks something like this:

{"fact":"Julius Ceasar, Henri II, Charles XI, and Napoleon were all afraid of cats.","length":74}
eeq64g8w

eeq64g8w1#

您需要在axios get头中添加带有“application/json”的Accept-Encoding

var axios = require('axios');
const getCatFact = async () => {
  const url = "https://catfact.ninja/fact";

  const response = await axios.request({
    method: 'GET',
    url: url,
    headers: {
        'Accept-Encoding': 'application/json'
    }
  });
  console.log(response.data);
};

getCatFact();

会是得到这种结果

$ node get-cat.js
{
  fact: 'Cats have about 130,000 hairs per square inch (20,155 hairs per square
centimeter).',
  length: 83
}

相关问题