Axios 封装

目标

页面只需要调用对应的方法处理返回数据及业务,不出现请求的具体代码

思路

  1. 将axios 封装,处理一些统一的逻辑.比如 header token auth 等

  2. 添加拦截器处理统一的状态

  3. 封装基础的请求方法

  4. 按照业务封装api,实现具体接口的请求

  5. 页面调用需要的接口方法,处理返回数据

实现(伪代码)

1. axios基础封装
import axios from "axios";

const instance = axios.create({
  baseURL: "...",
  timeout: 3000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    console.log(config);

    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response.data;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    if (error.response) {
      // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
      console.error(error.response.data);
      console.error(error.response.status);
      console.error(error.response.headers);
    } else if (error.request) {
      // 请求已经成功发起,但没有收到响应
      // `error.request` 在浏览器中是 XMLHttpRequest 的实例,
      // 而在node.js中是 http.ClientRequest 的实例
      console.error(error.request);
    } else {
      // 发送请求时出了点问题
      console.error("Error", error.message);
    }
    console.error(error.config);
    // return Promise.reject(error);
  }
);

const get = (url, params) => {
  return instance.get(url, { params });
};

const post = (url, data) => {
  return instance.post(url, data);
};

const put = (url, data) => {
  return instance.put(url, data);
};

const del = (url) => {
  return instance.delete(url);
};



export default {
  get,
  post,
  put,
  delete: del
};
2. 业务api封装
import api from "../axios";

export const getUserInfo = () => {
  return api.get("/userinfo");
};

export default {
  getUserInfo,
}
import api from "../axios";

const getPhotos = () => {
  return api.get("photos");
};
const getPosts = () => {
  return api.get("posts");
};
const getComments = () => {
  return api.get("comments");
};
const getAlbums = () => {
  return api.get("albums");
};
const getTodos = () => {
  return api.get("todos");
};

export default {
  getPhotos,
  getPosts,
  getComments,
  getAlbums,
  getTodos,
};
3. 页面使用

优点:

  1. 页面上不会有网络请求的代码,只处理业务相关的数据

  2. 接口有改动的时候,只需要修改对应的方法,由于按照业务进行了分类封装,目标明确,且数据格式不变的话可以不用动页面


Axios 封装
https://halo.jiangling.site/archives/axios
作者
你的降灵
发布于
2025年07月17日
许可协议