Although the use of AXIOS in VUE is very convenient, in practice, we may create a unified global method to simplify operations for the consistency of interface rules in daily operation. And in the actual interface docking, we mostly need to intercept the request and response for token and callback status code processing. Then, I made a simple installation based on my own needs (I had little contact with VUE before and mainly used NG and React, but I want to use VUE for this new project. I want to familiarize myself with some new features and methods of VUE, and welcome your criticism and correction if there is anything wrong).

Prerequisite: Familiar with front-end TS, Node, etc.

1. Install axios

npm install axios
Copy the code

2. Interceptor and global method writing

A http.ts file encapsulates its own HTTP logic. For code separation, I also create an interceptors.

Interceptors.ts (interceptor for request and response interception and partial logic processing)

   import axios from 'axios';
   import {message} from 'ant-design-vue';  // This is the antD component library I introduced to make it easier to pop toast
   
   export class Interceptors {
       public instance: any;
   
       constructor() {
           // Create an axios instance
           this.instance = axios.create({timeout: 1000 * 12});
           // Initialize the interceptor
           this.initInterceptors();
       }
       
       // To get the initialized axiOS instance in http.ts
       public getInterceptors() {
           return this.instance;
       }
   
   
       // Initialize the interceptor
       public initInterceptors() {
           // Set the POST header
           this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
           /** * Request interceptor * Each request is preceded by a token */ in the request header if it exists
           this.instance.interceptors.request.use(
               (config) = > {
                   // During login process control, users can be judged based on whether tokens exist locally
                   // But even if the token exists, it is possible that the token is expired, so the token is carried in the request header each time
                   // The background determines the login status of the user according to the token carried and returns the corresponding status code to us
                   if (config.headers.isJwt) {
                       const token = localStorage.getItem('id_token');
                       if (token) {
                           config.headers.Authorization = 'Bearer '+ token; }}return config;
               },
               (error) = > {
                   console.log(error); });// Response interceptor
           this.instance.interceptors.response.use(
               // The request succeeded
               (res) = > {
                   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 (res.status === 200) {
                       return Promise.resolve(res.data);
                   } else {
                       this.errorHandle(res);
                       return Promise.reject(res.data); }},// The request failed
               (error) = > {
                   const {response} = error;
                   if (response) {
                       // The request has been issued, but it is outside the scope of 2xx
                       this.errorHandle(response);
                       return Promise.reject(response.data);
                   } else {
                       // Handle network outages
                       // If the request times out or the network is disconnected, update the network status of state
                       // The network state controls the display and hiding of a global disconnection alert component in app.vue
                       // About the refresh of the disconnection component to retrieve data is explained in the disconnection component
                       message.warn('Network connection is abnormal, please try again later! '); }}); }/** * HTTP handshake error *@param The res response callback performs different operations according to the response */
       private errorHandle(res: any) {
           // Determine the status code
           switch (res.status) {
               case 401:
                   break;
               case 403:
                   break;
               case 404:
                   message.warn('Requested resource does not exist');
                   break;
               default:
                   message.warn('Connection error'); }}}Copy the code

Http.ts (HTTP encapsulation, handle according to the actual situation)

/ * * *@author  keiferju
 * @time    The 2019-08-29 12:57 *@title   HTTP request encapsulation *@desc* * /
import {Interceptors} from '@/service/interceptors';
import {message, Modal} from 'ant-design-vue';   / / is toast
import router from '.. /router';

export class HttpService {
    public axios: any;
    public modal: any;

    constructor() {
    		// Get the axios instance
        this.axios = new Interceptors().getInterceptors();
    }


    /** * get request *@param Params parameters *@param JWT Whether to verify the token *@param * modulename module@param The operation interface *@param Flag tag *@param Verson version, default 1.0.0 *@param Service Indicates the service. The default value is services */
    public getData(params: object, jwt: boolean, modulename: string, operation: string,
                   flag: string, verson = '1.0.0', service = 'services') {

        const url = service + '/' + verson + '/' + modulename + '/' + operation;
        const body = {
            parameter: {
                data: params,
                tag: flag,
            },
        };

        return new Promise((resolve, reject) = > {
            this.axios.get(url, {
                params: body,
                headers: {isJwt: jwt},
            }).then((res) = > {
                this.resultHandle(res, resolve);
            }).catch((err) = > {
                reject(err.message);
            });
        });

    }


    /** * Post request *@param Params parameters *@param JWT Whether to verify the token *@param * modulename module@param The operation interface *@param Flag tag *@param Verson version, default 1.0.0 *@param Service Indicates the service. The default value is services */
    public postData(params: object, jwt: boolean, modulename: string, operation: string,
                    flag: string, verson = '1.0.0', service = 'services') {
        const url = service + '/' + verson + '/' + modulename + '/' + operation;
        const body = {
            data: params,
            tag: flag,
        };
        return new Promise((resolve, reject) = > {
            this.axios.post(url, body, {
                headers: {isJwt: jwt},
            }).then((res) = > {
                this.resultHandle(res, resolve);
            }).catch((err) = > {
                reject(err.message);
            });
        });

    }


    / * * * *@param res
     * @param resolve* /
    public resultHandle(res: any, resolve) {
        if (res.status > 0) {
            resolve(res.data);
        } else {
            this.errorHandle(res); }}/** * Server state handling, such as interrupt exceptions, exit exceptions, etc. *@param res* /
    public errorHandle(res: any) {
        message.warn(res.msg);  // When we talk about the server prompt, we provide the prompt by the server
        // Determine the status code
        switch (res.status) {
            case -102: 
                 break;
            case -152:
                break;
            default:
            // console.log(other);}}}Copy the code

3. Mount

We define the interceptor, then we need to mount it globally, so that we can use it easily.

main.ts

import Vue from 'vue';
import App from './App.vue';
import HighchartsVue from 'highcharts-vue';

Vue.config.productionTip = false;

Vue.prototype.$httpService = new HttpService();  // Mount the service

new Vue({
    router,
    render: (h) = > h(App),
}).$mount('#app');
Copy the code

4. Ts Bridge Even (I don’t know what to call it, I have been calling it since NG)

$httpService does not exist. $httpService does not exist.

Create a xx.d.ts file in the parent directory of main.ts.

	import {HttpService} from './service/http';
   
declare module 'vue/types/vue' {
    interface Vue {
        $httpService: HttpService; }}Copy the code

5. Use

If this is used in a callback where the “this” reference has changed, it will not be found.

this.$httpService.postData({}, true.'execute'.'xxx'.'tag').then((result) = > {
             // doing            
}, (error) = > {
     console.log(error);
});
Copy the code

Finally: this is encapsulation under TS,js is a bit simpler, and should even be a bit simpler (fewer steps, online tutorials should be a lot more). The way HTTP tools are mounted is also suitable for defining global tool classes or services.

Welcome to my blog