我正在学习使用Axios,但输出如图所示,

当我使用FETCH时,输出是正常的.

我如何才能修复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 .

我try 使用Catch,但没有显示任何错误

推荐答案

需要在axios.get头中加上Accept-Encodingapplication/json.

Axios的缺省值为gzip

使用此代码

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();

结果

$ node timer.js
[
    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "Sincere@april.biz",
        "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

Javascript相关问答推荐

useNavigation更改URL,但不呈现或显示组件

Redux查询多个数据库Api reducerPath&

Next.js(react)使用moment或不使用日期和时间格式

如何修复(或忽略)HTML模板中的TypeScript错误?'

当Redux提供程序访问Reduxstore 时,可以安全地从Redux提供程序外部调用钩子?

将核心模块导入另一个组件模块时存在多个主题

如何迭代叔父元素的子HTML元素

JS:XML insertBefore插入元素

使用领域Web SDK的Vite+Vue应用程序中的Web程序集(WASM)错误

如何发送从REST Api收到的PNG数据响应

如何在DYGRAPS中更改鼠标事件和键盘输入

如何用javascript更改元素的宽度和高度?

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

rxjs在每次迭代后更新数组的可观察值

我们是否可以在reactjs中创建多个同名的路由

REACT-本机错误:错误类型错误:无法读取未定义的容器的属性

如何格式化API的响应

用内嵌的含selenium的Java脚本抓取网站

在特定区域的图像上 Select x和y,并在其上创建边框

Qualtrics联合实验脚本随机化条件