Axios package - vue3 project


foreword

The API of axios is very friendly and can be used directly in the project. However, in large-scale projects, there are many http requests, and the environment needs to be distinguished. Each network request has a similar part that needs to be processed, which will lead to code redundancy and damage the maintainability and scalability of the project. Therefore, it is necessary to correspondingly respond to axios requests encapsulation


text

install axios

# npm 安装
npm install axios
# yarn 安装
yarn add axios

Package request api

1. Create a new api directory under the src directory, put the request-related files in it, create a new request.jsfile, and import it firstaxios
import axios from 'axios';
2. Create an axiosinstance
// request.js
// 创建新的axios实例
const service = axios.create({
    
    
  // 环境变量,需要在.env文件中配置
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时时间暂定5s
  timeout: 5000,
});
3. Axios request interceptor

Configure some processing before the request in config, such as: data conversion, configuration request header, setting token, setting loading, etc., add according to requirements

// request.js
service.interceptors.request.use(
  config => {
    
    
  	// 此处添加Loading
    return config;
  },
  error => {
    
    
    return Promise.reject(error);
  }
);

Add next Loading, use vantthe component Toastprompt, so import it first vant, and the same goes for other UI libraries

# Vue 3 项目,安装最新版 Vant
npm i vant
# 通过 yarn 安装
yarn add vant
// request.js
// 使用vant组件的Toast提示,import引入要放在项目最上方
import {
    
     showToast, showLoadingToast, closeToast, setToastDefaultOptions } from 'vant';
import 'vant/es/toast/style';
//显示持续时长
setToastDefaultOptions({
    
     duration: 3000 }); 

// loading 次数
let loadingCount = 0;

service.interceptors.request.use(
  config => {
    
    
    // 加入Loading
    showLoadingToast({
    
    
      message: '加载中...',
      //禁止背景点击
      forbidClick: true,
    });
    loadingCount++;
    return config;
  },
  error => {
    
    
    return Promise.reject(error);
  }
);
4. Axios response interceptor
// request.js
service.interceptors.response.use(
  response => {
    
    
    // 关闭loading
    loadingCount--;
    if (loadingCount === 0) {
    
    
      closeToast();
    }
    return response;
  },
  error => {
    
    
    closeToast();
    // 处理异常情况,根据项目实际情况处理或不处理
    if (error && error.response) {
    
    
      // 根据约定的响应码处理
      switch (error.response.status) {
    
    
        case 403:
          error.message = '拒绝访问';
          break;
        case 502:
          error.message = '服务器端出错';
          break;
        default:
          error.message = `连接错误${
      
      error.response.status}`;
      }
    } else {
    
    
      // 超时处理
      error.message = '服务器响应超时,请刷新当前页';
    }
    showToast(error.message);
    return Promise.resolve(error.response);
  }
);
5. Encapsulate the request function, which can process parameters according to the actual situation of the project (only get and post requests are processed here)
// request.js
const Request = (url, options = {
     
     }) => {
    
    
  let method = options.method || 'get';
  let params = options.params || {
    
    };
  
  if (method === 'get' || method === 'GET') {
    
    
    return new Promise((resolve, reject) => {
    
    
      service
        .get(url, {
    
    
          params: params,
        })
        .then(res => {
    
    
          if (res && res.data) {
    
    
            resolve(res.data);
          }
        })
        .catch(err => {
    
    
          reject(err);
        });
    });
  } else {
    
    
    return new Promise((resolve, reject) => {
    
    
      service
        .post(url, params)
        .then(res => {
    
    
          if (res && res.data) {
    
    
            resolve(res.data);
          }
        })
        .catch(err => {
    
    
          reject(err);
        });
    });
  }
};
6. Finally export the function method
// request.js
export default Request;

How to use

1. All interfaces can be defined in one file (easy to manage)

Create a new file in the same directory as the request.js fileindex.js

// index.js
import http from './request';

export function getXXX() {
    
    
  return http('/api/get');
}

export function postXXX(params) {
    
    
  return http('/api/post', {
    
    
    method: 'POST',
    params: params,
  });
}

Then import in the project

import {
    
     getXXX, postXXX } from "./api/index";
getXXX().then(res => {
    
    
	// ...
});
let params = {
    
    
  pageNum: 1,
  pageSize: 10,
};
postXXX(params).then(res => {
    
    
	// ...
});
2. Another way of writing is to use it directly in the project
import http from "./api/request";

http('/api/get').then(res => {
    
    
	// ...
});

let params = {
    
    
  pageNum: 1,
  pageSize: 10,
};
http('/api/post', {
    
    
  method: 'POST',
  params: params,
}).then(res => {
    
    
	// ...
});;

Summarize

This article uses the vue3+vant4 project example to introduce how to encapsulate axios requests in the project. In fact, the writing method in vue2 is similar. There is no absolute standard for axios encapsulation, and it needs to be designed in combination with the actual scene in the project.

If this article is helpful to you, you are welcome to [Like], and you are also welcome to [Comment] + [Favorite]!


further reading

  1. Axios Chinese Documentation
  2. Vant4 Toast

Guess you like

Origin blog.csdn.net/m0_55119483/article/details/129686563