Skip to content

Axios 拦截器请求拦截-响应拦截

一、看一遍 Axios 官网文档

https://axios-http.com/zh/docs/interceptors

二、项目中封装 axios

@/utils/request.js

js
import axios from 'axios';

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL,
  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // 默认的 发送cookieshen跨域请求
  timeout: 1000 * 60 // 请求超时
});
// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

三、/api 目录下统一管理所有的请求

/api/order.js

javascript
/**
 * @file 订单管理
 * @author 程序员李钟意
 */
import request from '@/utils/request';

export function getApiList(params) {
  return request({
    method: 'get',
    url: '/api/orders/',
    params
  });
}
export function postApiList(data) {
  return request({method: 'post', url: '/api/orders/', data});
}
export function putApisList(data) {
  return request({method: 'put', url: '/api/orders/', data});
}
export function putApiList(id, data) {
  return request({method: 'put', url: `/api/orders/${id}/`, data});
}
export function getApiById(id) {
  return request({method: 'get', url: `/api/orders/${id}/`});
}
export function deleteApiById(id) {
  return request({method: 'delete', url: `/api/orders/${id}/`});
}
export function deleteApiByIds(ids) {
  return request({method: 'delete', url: '/api/orders/', data: ids});
}

四、在 Vue 项目中使用

index.vue

vue
<script>
import {getApiList} from '@/api/order';

export default {
  name: 'order',
  components: {},
  data() {
    return {};
  },
  computed: {},
  watch: {},
  created() {
    this.getList();
  },
  beforeDestroy() {},
  methods: {
    // 获取列表数据
    getList() {
      this.isLoading = true;
      getApiList(newItem)
        .then(({data: res}) => {
          if (res.status === 200) {
            const {data, count, page, pageSize} = res;
            this.tableData = data;
            this.formSearch = {...this.formSearch, page, pageSize, count};
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .finally(() => (this.isLoading = false));
    }
  }
};
</script>