Axios GET 返回不可读的响应

Ork*_*zen 10 node.js express axios

我有一个带有 axios (1.2.0) 的简单 GET 的 Express 应用程序:

\n
const result: AxiosResponse = await axios.get('https://jsonplaceholder.typicode.com/posts')\n
Run Code Online (Sandbox Code Playgroud)\n

result.data 最终是一个神秘的、编码错误的字符串:

\n
k\xef\xbf\xbdH\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd>\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdT\xef\xbf\xbd\xef\xbf\xbdN.\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdr\xef\xbf\xbdH\xef\xbf\xbdv \xef\xbf\xbd_"9'?1\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdJ\xef\xbf\xbd\xef\xbf\xbd\\\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbdLA.  \xef\xbf\xbd\xef\xbf\xbdH\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd!\xef\xbf\xbdb\xef\xbf\xbdR\xef\xbf\xbd 9\xef\xbf\xbd\xdc\x85\xef\xbf\xbd\xef\xbf\xbd\xda\xb9\xef\xbf\xbdK\xef\xbf\xbd}\xef\xbf\xbd\xef\xbf\xbd%\xef\xbf\xbd\xef\xbf\xbdA\xef\xbf\xbdv\xef\xbf\xbdQ*\xef\xbf\xbdg\xef\xbf\xbddwf\xef\xbf\xbd ..goes long\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试过在请求中添加不同的配置,但没有成功。\n在其他地方也找不到任何相关帖子。

\n

为什么会这样呢?我该如何解决它?

\n

Ben*_*Vue 9

在 v1.2.1 中修正了这个错误。

您需要Accept-Encoding在 axios.get 标头中添加 application/json 。

它的默认值是gzip

您可以使用 1.2 与此代码

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();
Run Code Online (Sandbox Code Playgroud)

结果

$ 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
Run Code Online (Sandbox Code Playgroud)