Axios返回JSONPlaceholder的乱码



我正在尝试学习使用Axios获取API数据(最终与HubSpot API一起工作)。我已经建立了一个小的测试项目,我试图从JSONPlaceholder和RapidAPI FamousQuotes API检索数据,使用fetch和Axios。

使用Axios和fetch的代码示例,一切都可以正常使用Rapid API。但是当我使用相同的代码来瞄准JSONPlacholder时,我得到了奇怪的结果。下面是使用fetch的代码,它可以工作:

//import node-fetch
const url = 'https://jsonplaceholder.typicode.com/posts';
const options = {
method: 'GET',
headers: {}
};
fetch(url, options)
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error('error:' + err));

返回
[
{
userId: 1,
id: 1,
title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body: 'quia et suscipitn' +
etc ...

然而,如果我使用axios,我会得到一些奇怪的东西:

const axios = require('axios')
const url = 'https://jsonplaceholder.typicode.com/posts';
const options = {
method: 'GET',
url: url,
headers: {}
};
axios.request(options).then(function (response) {
console.log(response);
}).catch(function (error) {
console.error(error);
});

返回乱码文本:

`x13x7Fk�H��x01�bx1D>����x15��T��Nx1B.x16���r�H�vx1E �_"9x18'?1�x13��J��\���LA.t��Hx17���x10x9B!�b�x12x04R� 9�܅��ڹ�x0EK�}��%��Ax12�v�x15Q*�g�dwf�n` +
'�ئ��iQ��}���0tx18c�?�߾������Kx05�_��/y���x1E/�x1D�9��K^�,E+�vx1C���95��6���xIyu��x0E�]x1C��x07:�w��a�,�{�|��嗼�n' +
'R���b6��x1B�A�Px1Bn' +
'�n�]eYG�0�w��^�ك�ee�D$x15R)��KC�SW3��SKx0EN-Ax04�x92x18���x12<`D�+��oJ���/"��x03jx03�V��x18�x14x11�{��]|�ĺ�@x1ELE��_BtZ���t�w��ӏܠ�x10赿5Bf���w}RSnSm0ɐ�ϺRx13r�9.x0F��3Px7F�x03v�x06��.�^8�%�&x037&C^��x0B�n' +

我试过强制响应类型为"text"或者将编码改为"utf8"没有成功。奇怪的是,当用这两种方法瞄准"https://famous-quotes4.p.rapidapi.com/random"时,我在两种情况下都得到了适当的响应。我可能错过了什么,但我不知道是什么…

在v1.2.1中修复了此错误。

在Axios Get头中添加Accept-Encodingapplication/json。这是v1.2.0的缺陷

这是已知的缺陷。

在axios v1.2.0中默认为gzip

const axios = require('axios')
const url = 'https://jsonplaceholder.typicode.com/posts';
const options = {
method: 'GET',
url: url,
headers: {
'Accept-Encoding': 'application/json'
}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});

结果

$ node get-data.js
[
{
userId: 1,
id: 1,
title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body: 'quia et suscipitn' +
'suscipit recusandae consequuntur expedita et cumn' +
'reprehenderit molestiae ut ut quas totamn' +
'nostrum rerum est autem sunt rem eveniet architecto'
},
{
userId: 1,
id: 2,
title: 'qui est esse',
body: 'est rerum tempore vitaen' +
'sequi sint nihil reprehenderit dolor beatae ea dolores nequen' +
'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisn' +
'qui aperiam non debitis possimus qui neque nisi nulla'
},
...

相关内容

最新更新