教程 axios tutorial

创建 Axios 实例

在大型前端项目中,为了应对多个后端接口或不同配置需求,通常会创建 Axios 实例,实现独立定制化配置。

1. 基本实例创建

javascript
import axios from "axios";

const api = axios.create({
  baseURL: "https://api.example.com", // 基础请求 URL
  timeout: 5000, // 请求超时时间(毫秒)
  headers: {
    "Content-Type": "application/json",
  },
});

export default api;

2. 使用 Axios 实例发送请求

javascript
import api from "./api";

api
  .get("/users/123")
  .then((res) => console.log("用户数据:", res.data))
  .catch((err) => console.error("请求失败:", err));

3. 实例优势

  • 独立配置:每个实例可以有不同 baseURL、headers 或 timeout;
  • 便于扩展:可为实例单独设置请求/响应拦截器;
  • 提高维护性:多个后端服务可使用不同实例,避免全局配置冲突。

💡 小提示:在项目中合理使用 Axios 实例可以让接口请求逻辑更清晰、统一,并方便对不同服务或环境进行定制化配置。