As a front-end developer, each project basically needs to interact with the background. At present, the most popular Ajax library is Axios. Of course, some students also choose the Request plug-in. Currently, axios has config, interceptor, and various request methods, but for a large project, we still need to do secondary encapsulation to quickly improve development efficiency!

Today we’re going to re-wrap the AXIos library to see if we can simplify our development efforts.

Create a project

  vue create axios-demo

Copy the code

Create a directory

// Enter the project space

  cd axios-demo

// Create the API directory under SRC

Copy the code

Create three files (index. Js/interceptor. Js/request. Js)

/ * *

 * index.js

* API address management

* /


export default {

    login:'/user/login'.

    getInfo:'/user/getInfo'

}

Copy the code

Index. js actually has nothing to do with the AXIos wrapper because it’s part of the API layer, so I created it together. I personally extract all project urls here for centralized management.

Encapsulation interceptor

Interceptor serves as an interceptor. It can intercept request parameters and response results. Generally, in projects, we mainly intercept interface errors, network errors, system timeout, permission authentication, etc.

Here we create the instance through create, set baseUrl, timeout, and then set request and Response interception.

/ * *

Generate basic AXIOS objects and handle requests and responses

* The back-end convention interface returns the deconstruction specification

 * {

 *    code:0,

* data:" success ",

 *    message:""

*}

* /


import axios from 'axios'

import { Message } from 'element-ui'



// Create a separate instance of AXIos

const service = axios.create({ 

    // Set the baseUr address. If you use proxy to cross domains, enter the Base address directly

    baseURL: '/api'.

    // Define a unified request header

    headers: {

        post: {

            "Content-Type""application/x-www-form-urlencoded; charset=UTF-8"

        }

    },

    // Set the request timeout period

    timeout: 10000.

    If JSONP is used, you can configure this parameter with cookie credentials. If proxy and CORS are used, you do not need to set this parameter

    withCredentials: true

});

// Request interception

service.interceptors.request.use(config= > {

    // Create a custom header to add project tokens

    config.headers.token = 'token';

    return config;

});

// Return interception

service.interceptors.response.use((response) = >{

    // Get the result of the interface return

    const res = response.data;

    // code is 0, so the front end doesn't have to fetch data again.

    if(res.code === 0) {

        return res;

    }else if(res.code === 10000) {

        // 10000 Indicates the login status code

        Message.warning(res.message);

        // You can also jump to the router

        window.location.href = '/#/login';

        return res;

    }else{

        // Error display can be controlled in service because there are certain scenarios where we don't want to show errors

        // Message.error(res.message);

        return res;

    }

= > {}, ()

    Message.error('Network request is abnormal, please try again later! ');

});

export default service;

Copy the code

If CORS/JSONP needs to differentiate the environment, you can use process.env.node_env to select which address to use. If a proxy is used, the Vue project needs to add environmental judgments to the proxy in vue.config.js.

process.env.NODE_ENV=== "production" ? "http://www.prod.com/api" : "http://localhost/:3000/api"

Copy the code

The above is a secondary wrapper for interceptor. We don’t include regular errors because we want to control whether errors are displayed later, so we will handle them in the Request.

Encapsulation axios

Create a request file, encapsulate axios for business development, and many times architects create a common mechanism to suit their own project needs, rather than trying to do everything, so this needs to be tweaked. For example, we only use GET/POST requests.

/ * *

 * request.js

* Perform secondary encapsulation for AXIos through promise, and make flexible configuration for user parameters

* /


import { Message,Loading } from 'element-ui';

import instance from './interceptor'



/ * *

* Core functions that handle all requested data and scale horizontally

* @param {url} requests the address

* @param {params} request parameters

* @param {options} request configuration for the current request;

* @param loading Whether to display loading

* @param Mock Whether to request mock this time instead of online

* @param error Indicates whether an error is displayed this time

* /


function request(url,params,options={loading:true,mock:false,error:true},method){

    let loadingInstance;

    // Pre-loading

    if(options.loading)loadingInstance=Loading.service();

    return new Promise((resolve,reject) = >{

        let data = {}

        // Get requests use the params field

        if(method =='get')data = {params}

        // The POST request uses the data field

        if(method =='post')data = {data}

        // Mock the local interface through the mock platform

        if(options.mock)url='http://www.mock.com/mock/xxxx/api';

        instance({

            url,

            method,

. data

        }).then((res) = >{

            // This is very useful and can extend many functions.

            // For example, if the data structure is inconsistent, it can be used as an interface adapter

            // Return date/amount/number can also be centralized processing

            if(res.status === 0) {

                resolve(res.data);

            }else{

                // You can configure to turn off the error message

                if(options.error)Message.error(res.message);

                reject(res);

            }

        }).catch((error) = >{

            Message.error(error.message)

        }).finally((a)= >{

            loadingInstance.close();

        })

    })

}

// Encapsulate the GET request

function get(url,params,options){

    return request(url,params,options,'get')

}

// Encapsulate the POST request

function post(url,params,options){

    return request(url,params,options,'post')

}

export default {

    get,post

}

Copy the code

Request. js mainly encapsulates axios to block all front-end requests. In this way, front-end loading effects, mocks, error blocking, error pop-up display, data adaptation, parameter adaptation, and environment adaptation can be done.

Now, how do we use it

  • Open the main js
// Import the plug-in

import request from './api/request'

// Extend the prototype so that you don't have to import Request on every page

Vue.prototype.request = request;

Copy the code
  • Request calling
  this.request.get('/login', {userName:'admin'.userPwd:'admin'}).then((res={}) = >{

        // Only successful data is received. Failed data is not returned

  }).catch((a)= >{

      // If you want to catch an exception, add it

  })

Copy the code

Without secondary packaging, it would be difficult for us to achieve the above function points. These are some personal experiences summed up after the company made many medium-sized background systems. I believe you will have some inspiration and help after reading them.

If you are interested, please pay attention to my personal wechat public number: Front-end future