# 使用 Axios

URL: https://caijiao.org/chartjs/07-backend/02-axios
Source: docs/chartjs/07-backend/02-axios.md
Description: 介绍如何使用 Axios 库替代 fetch 来请求 API 数据，并在 Chart.js 中动态更新图表，实现更加简洁和强大的异步数据处理。

[Chart.js](/chartjs/) 的数据可以通过多种方式异步获取。Axios 是一个基于 Promise 的 HTTP 客户端，使用简洁，支持拦截器和请求取消等功能，适合复杂场景。

下面示例展示如何用 Axios 请求数据，并更新折线图的数据内容。

```js
const ctx = document.getElementById("axiosChart").getContext("2d");

const axiosChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: [],
    datasets: [
      {
        label: "访问量",
        data: [],
        backgroundColor: "rgba(255, 159, 64, 0.7)",
      },
    ],
  },
  options: {
    responsive: true,
    plugins: {
      legend: { display: true },
    },
  },
});

// 使用 Axios 获取数据
axios
  .get("https://jsonplaceholder.typicode.com/comments?_limit=5")
  .then((response) => {
    const data = response.data;
    axiosChart.data.labels = data.map((item) => "评论ID " + item.id);
    axiosChart.data.datasets[0].data = data.map((item) => item.body.length);
    axiosChart.update();
  })
  .catch((error) => {
    console.error("Axios 请求失败", error);
  });
```

[在线代码演示](/chartjs/demos/25.html)
