Three encapsulations of axios--what are encapsulated

1. The first encapsulation: Encapsulate all requests in the project to do the same thing (baseURL, timeout, request/response, success or failure prompt) into a folder, which is usually called utils.

// axios封装-通用工具函数
// 引入axios
import axios from 'axios'
// 服务器地址 写上以后 所有的请求 会自动在前面拼接这个地址
axios.defaults.baseURL = 'http://127.0.0.1:5000';
axios.defaults.timeout = 3000;  // 超时
 
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
 
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

2. The second encapsulation: Divide all requests in the project into modules and encapsulate them in a folder, usually called api, which is convenient for unified management and maintenance of request addresses, and can do some personalized processing in specified modules

// 引入通用工具函数
import request from "@/utils/request"
 
【方式1】
// post封装
export const 变量名 = data=>{
    return request({
        url:'路径',
        method:'post',
        data
    })
}
 
// get封装
export const 变量名 = params =>{
    return request({
        url:'路径',
        method:'get',
        params
    })
}
 
【方式2】
export function 变量名(params) {
  return request.get("路径", params);
}

3. The third encapsulation: call the method encapsulated in the second layer directly in the business component (in the vue component), request the interface to obtain data, and use async and await to synchronize the asynchronous code when calling

Supplement ing

Reference link: Triple encapsulation of axios_Axios three-layer encapsulation_Raindrop 2000's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/coinisi_li/article/details/129157057