This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

One, foreword

This article is not related to Vite, the next article is about the configuration of environment variables is related to Vite, today here mainly talk about the actual use of AXIOS in VUe3 and the unified management of Api, hand in hand teaching hope you can touch the spark of inspiration here, flying colorful thoughts.

2. Directory structure

SRC directory to create API file,

  • api.tsManage interfaces and apis in a unified manner
  • axios.tsEncapsulate the request configuration interceptor
  • status.tsThe status code returned by the management interface

Third, axios. Ts

Line by line within the code

import axios from 'axios';
import { showMessage } from "./status";   // Import the status code file
import { ElMessage } from 'element-plus'  // Introduce the el prompt box, which component library is used in this project

// Set the interface timeout period
axios.defaults.timeout = 60000;

// Request address, which is a dynamically assigned environment variable, will be covered in detail in the next article
// @ts-ignore
axios.defaults.baseURL = import.meta.env.VITE_API_DOMAIN;   

// HTTP request interceptor
axios.interceptors.request.use(
  config= > {
  // Configure the request header
    config.headers = {
      //' content-type ':'application/x-www-form-urlencoded', // Coded input form
      'Content-Type':'application/json; charset=UTF-8'.// Parameter transmission mode JSON
      'token':'80c483d59ca86ad0393cf8a98416e2a1'              // Here is the custom configuration, here is the token pass
    };
    return config;
  },
  error= > {
    return Promise.reject(error); });// HTTP Response interceptor
axios.interceptors.response.use(
  response= > {
    return response;
  },
  error= > {
    const {response} = error;
    if (response) {
      // The request has been issued, but it is outside the scope of 2xx
      showMessage(response.status);           // Pass in the response code and match the corresponding information of the response code
      return Promise.reject(response.data);
    } else {
      ElMessage.warning('Network connection is abnormal, please try again later! '); }});// Encapsulate the GET POST request and export it
export function request(url=' ',params={},type='POST'){
// Set the default value of url params type
return new Promise((resolve,reject) = >{
  let promise
  if( type.toUpperCase()==='GET' ){
    promise = axios({
      url,
      params
    })
  }else if( type.toUpperCase()=== 'POST' ){
    promise = axios({
      method:'POST',
      url,
      data:params
    })
  }
  // Processing returns
  promise.then(res= >{
    resolve(res)
  }).catch(err= >{
    reject(err)
  })
})
}
Copy the code

Four, the status of ts

I don’t want to explain it. Just stick it out

export const showMessage = (status:number|string) : string= > {
    let message:string = "";
    switch (status) {
        case 400:
            message = "Request error (400)";
            break;
        case 401:
            message = "Unauthorized, please log in (401) again";
            break;
        case 403:
            message = "Access denied (403)";
            break;
        case 404:
            message = "Error request (404)";
            break;
        case 408:
            message = "Request timed out (408)";
            break;
        case 500:
            message = "Server error (500)";
            break;
        case 501:
            message = "Service Not Realized (501)";
            break;
        case 502:
            message = "Network error (502)";
            break;
        case 503:
            message = "Service unavailable (503)";
            break;
        case 504:
            message = "Network Timeout (504)";
            break;
        case 505:
            message = "HTTP version not supported (505)";
            break;
        default:
            message = 'Connection error (${status})! `;
    }
    return `${message}Please check the network or contact the administrator! `;
};
Copy the code

Five, the API. Ts

The request exported by AXIOS is introduced to manage interfaces according to functional modules

import { request } from './axios'

/ * * *@description - Encapsulates the User interface method */
export class UserService {       / / module
    / * * *@description User login@param {string} username- User name *@return {HttpResponse} result* /
    static async login1(params) {   / / interface
        return request('/login',params, 'post')}static async login2(params) {   / / interface
        return request('/login',params, 'post')}static async login3(params) {   3 / / interface
        return request('/login',params, 'post')}}export class landRelevant {     / / module 2
    / * * *@description Gets the list of places *@return {HttpResponse} result* /
    static async landList(params) {
        return request('/land_list_info',params, 'get')}}Copy the code

Six, application

There is no need to introduce it in main.ts. What module interface is needed to introduce the modified module in the corresponding page

<script setup>
import { onMounted } from "vue";
import {UserService} from '/src/api/api.ts'

onMounted(() = >{
  login1()
  login2()
})

const login1 = async() = > {const loginParams = {
    username: 'test'.password: 'test',}const res = await UserService.login1(loginParams)
  // console.log(res)
}

const login2 = () = > {
  const loginParams = {
    username: 'test'.password: 'test',
  }
  UserService.login2(loginParams).then((res) = >{
    // console.log(res)
  })
}
</script>
Copy the code

Vii. Concluding remarks

Today, when I was configuring the project, I searched many articles related to Vue3 AXIOS on the Internet, and found that there was no content that fully met my needs. Therefore, I finally collected hundreds of articles to integrate such an article, hoping to be helpful to you

My blog is synchronized to tencent cloud + community, invite everyone to come together: cloud.tencent.com/developer/s…