The vUE project is used as an example to describe the problems of configuring AXIOS in TS edition.

./package.json uses Axios. The UI is arbitrary, so I’m using Element-Plus

{..."dependencies": {..."element-plus": "^ - beta 1.0.1. 21"."axios": "^ 0.21.1". },... }Copy the code

Added the/SRC/API /request.ts file.

import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import { ElMessage } from 'element-plus'
 
export class Request {
    public static axiosInstance: AxiosInstance;

    // constructor() {
    // // Create the Axios instance
    // this.axiosInstance = axios.create({timeout: 1000 * 12});
    // // Initializes the interceptor
    // this.initInterceptors();
    // }

    public static init() {
        // Create the Axios instance
        this.axiosInstance = axios.create({
            baseURL: process.env.VUE_APP_BASE_URL + '/api/v1'.timeout: 6000
        });
        // Initialize the interceptor
        this.initInterceptors();
        // return axios;
    }

    // To get the initialized Axios instance in http.ts
    // public getInterceptors() {
    // return this.axiosInstance;
    // }

    // Initialize the interceptor
    public static initInterceptors() {
        // Set the POST request header
        this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        /** * Request interceptor * carries the token */ in the request header if it exists before each request
        this.axiosInstance.interceptors.request.use(
            (config: AxiosRequestConfig) = > {
 
                // const token = Vue.ls.get(ACCESS_TOKEN)
                // if (token) {
                // config.headers['Authorization'] = 'Bearer ' + token
                // }
 
                // In the login process control, the login status of a user is determined based on the local token
                // However, even if the token exists, it may be expired, so carry the token in each request header
                // The background determines the login status of the user according to the token carried and returns the corresponding status code
                // if (config.headers.isJwt) {
                    const token = localStorage.getItem('ACCESS_TOKEN');
                    if (token) {
                        config.headers.Authorization = 'Bearer ' + token;
                    }
                // }
                return config;
            },
            (error: any) = > {
                console.log(error); });// Respond to interceptors
        this.axiosInstance.interceptors.response.use(
            // The request succeeded
            (response: AxiosResponse) = > {
                // if (res.headers.authorization) {
                // localStorage.setItem('id_token', res.headers.authorization);
                // } else {
                // if (res.data && res.data.token) {
                // localStorage.setItem('id_token', res.data.token);
                / /}
                // }
 
                if (response.status === 200) {
                    // return Promise.resolve(response.data);
                    return response;
                } else {
                    Request.errorHandle(response);
                    // return Promise.reject(response.data);
                    returnresponse; }},// The request failed
            (error: any) = > {
                const {response} = error;
                if (response) {
                    // The request has been sent, but it is not in the scope of 2xx
                    Request.errorHandle(response);
                    return Promise.reject(response.data);
                } else {
                    // Handle the case of network disconnection
                    // eg: Update the state of the network when the request times out or the network is disconnected
                    // The network status in app.vue controls the display and hide of a global disconnection prompt component
                    // Refresh and retrieve data in the disconnection component will be described in the disconnection component
                    ElMessage.warning(The network connection is abnormal, please try again later! '); }}); }/** * HTTP handshake error *@param Res response callback. Different operations are performed according to different responses */
    private static errorHandle(res: any) {
        // Check the status code
        switch (res.status) {
            case 401:
                break;
            case 403:
                break;
            case 404:
                ElMessage.warning('Requested resource does not exist');
                break;
            default:
                ElMessage.warning('Connection error'); }}}Copy the code
  • Request. Ts encapsulatesRequestMethod, useclassSyntax sugar is created during the processaxiosInstance
  • Because the use oftsVersion fromaxiosReferenced in the dependencyAxiosInstance,AxiosRequestConfig,AxiosResponse, these three belong to interfacesinterface.
  • RequestClass implementation includes creating instancesthis.axiosInstance, initializes interceptors, which include response interceptors and request interceptors. Request interception settoken, the response intercept handled the error logic.
  • baseURLIn theprocess.env.VUE_APP_BASE_URLIs obtained through the.env.development configuration.

.env.development

= 'development' NODE_ENV VUE_APP_BASE_URL = 'http://0.0.0.0:8899'Copy the code

Corresponds to the script in./package.json

{..."scripts": {
    "serve": "vue-cli-service serve --mode development"."build": "vue-cli-service build --mode production"},... }Copy the code

/ SRC /main.ts introduces the request.ts that you just created

.import { Request } from '@/api/request';
const app = createApp(App as any) Request.init(); .Copy the code

Add/SRC/API /api.ts file, randomly create a login interface test.

import { Request } from './request';
export function login (parameter: any)  {
  return Request.axiosInstance({
    url: '/login'.method: 'post'.data: parameter
  })
}
Copy the code

Use a random page, such as/SRC /views/ home.vue

import { defineComponent, onMounted } from 'vue';
import { login } from '@/api/api';
export default defineComponent({
  name: 'Home'.setup() {
  	onMounted(() = >{
      login({
        username:'admin'.password:'123456'}); }}}));Copy the code
  • withComposition API
  • Introduce what I just wrotelogininterface
  • OnMounted methodlogin
  • Can be achieved bynodejsTo create aloginInterface testing.