SoFunction
Updated on 2025-04-05

Vue application instance code encapsulated based on axios request

What is axios?

Axios is a promise-based HTTP library that can be used in browsers and .

characteristic:

  • Create XMLHttpRequests from the browser
  • Create http request from
  • Support Promise API
  • Intercept requests and responses
  • Convert request data and response data
  • Cancel request
  • Automatically convert JSON data
  • Client-supported defense XSRF

Promises

axios is supported by relying on the native ES6 Promise implementation. If your environment does not support ES6 Promise, you can use polyfill.

Request type of axios?

Install a set of environments for node:

Here are three citation methods:
npm install axios - First install axios in node, and just introduce axios in the API package.
bower install axios -- install bower in npm, and introduce axios package in bower

bower:
Bower can manage components that contain HTML, CSS, JavaScript, fonts, and even image files. Bower does not concatenate or shrink the code or perform anything else - it will only install the correct version of the package and its dependencies required.
Directly import js files in vue
<script src="/axios/dist/"></script>

Axios encapsulates default custom configuration

const instance = ({
{
   // `url` is the server URL used for request  url: '/user',

  // `method` is the method used when creating a request  method: 'get', // default

  // `baseURL` will be automatically added before `url` unless `url` is an absolute URL.  // It can facilitate the passing of relative URLs to the axios instance method by setting a `baseURL`  baseURL: '/api/',

  // `transformRequest` allows modification of request data before sending to the server  // Only use the request methods of 'PUT', 'POST' and 'PATCH'  // The function in the following array must return a string, or an ArrayBuffer, or a Stream  transformRequest: [function (data, headers) {
    // Perform arbitrary conversion of data    return data;
  }],

  // `transformResponse` is allowed to modify the response data before being passed to then/catch  transformResponse: [function (data) {
    // Perform arbitrary conversion of data    return data;
  }],

  // `headers` is a custom request header to be sent soon  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` is the URL parameter to be sent with the request  // Must be a plain object or URLSearchParams object  params: {
    ID: 12345
  },

   // `paramsSerializer` is a function responsible for `params` serialization  // (. /package/qs, //)
  paramsSerializer: function(params) {
    return (params, {arrayFormat: 'brackets'})
  },

  // `data` is data sent as the requesting body  // Applicable only to these request methods 'PUT', 'POST', and 'PATCH'  // When `transformRequest` is not set, it must be one of the following types:  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser exclusive: FormData, File, Blob  // - Node exclusive: Stream  data: {
    firstName: 'Fred'
  },

  // `timeout` specifies the number of milliseconds for the request timeout (0 means no timeout)  // If the request charge exceeds the timeout, the request will be interrupted  timeout: 1000,

   // `withCredentials` indicates whether credentials are required when requesting across domains  withCredentials: false, // default

  // `adapter` allows custom processing of requests to make testing easier  // Return a promise and apply a valid response (see [response docs](#response-api)).  adapter: function (config) {
    /* ... */
  },

 // `auth` means that HTTP basic verification should be used and credentials are provided  // This will set an `Authorization` header, overwriting any existing custom `Authorization` header set using `headers`  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

   // `responseType` represents the data type of the server response, which can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

   // `xsrfCookieName` is the name of the cookie used as the value of xsrf token  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

   // `onUploadProgress` allows processing of progress events for uploads  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows processing of progress events for downloads  onDownloadProgress: function (progressEvent) {
    // Handling of native progress events  },

   // `maxContentLength` defines the maximum size of the allowed response content  maxContentLength: 2000,

  // `validateStatus` defines the status code for the given HTTP response to be resolve or reject promise .  If `validateStatus` returns `true` (or set to `null` or `undefined`), the promise will be resolved; otherwise, the promise will be rejected  validateStatus: function (status) {
    return status &gt;= 200 &amp;&amp; status &lt; 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects in follow  // If set to 0, no redirects will be followed  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in .
  // . '/var/run/' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` are used in ``httpsAgent` to define the custom proxy used when executing http and https, respectively.  Allows configuring options like this:  // `keepAlive` is not enabled by default  httpAgent: new ({ keepAlive: true }),
  httpsAgent: new ({ keepAlive: true }),

  // 'proxy' defines the host name and port of the proxy server  // `auth` means that HTTP basic authentication should be used for connection proxy and provide credentials  // This will set a `Proxy-Authorization` header, overwriting the existing custom `Proxy-Authorization` header set using `header`.  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies the cancel token used to cancel the request  // (See the Cancellation section below to learn more)  cancelToken: new CancelToken(function (cancel) {
  })
}
}).then(function(response){
// `data` Response provided by the server  data: {},

  // `status` HTTP status code from server response  status: 200,

  // `statusText` HTTP status information from the server response  statusText: 'OK',

  // `headers` server response header  headers: {},

   // `config` is the configuration information provided for the request  config: {},
 // 'request'
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in  (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
});

Configured loading priority

High to Low order:

Step 1: Configure the default value

Configuration Items Set in Request

('/longRequest', {
 timeout: 5000
});

Part 2: Global axios default value

Configuration items set in the api file

 = 2500;

Step 3: Customize the default value of the instance

Configuration Items Set in Creating Axios Instance

var instance = ();

Interceptor

// Add a request interceptor(function (config) {
    // What to do before sending a request    return config;
  }, function (error) {
    // What to do about the request error    return (error);
  });

// Add a response interceptor(function (response) {
    // Do something about the response data    return response;
  }, function (error) {
    switch () {
      case 400:
         = 'Bad Request';
        break;
      case 401:
         = 'Not authorized, please log in again';
        break;
      case 403:
         = 'access denied';
        break;
      case 404:
         = 'Request error, the resource was not found';
        break;
      case 405:
         = 'Request method is not allowed';
        break;
      case 408:
         = 'Request timed out';
        break;
       case 415:
         = 'The server cannot process the media format that comes with the request';
        break;
      case 500:
         = 'The server error';
        break;
      case 501:
         = 'Network not implemented';
        break;
      case 502:
         = 'Network Error';
        break;
      case 503:
         = 'Service is not available';
        break;
      case 504:
         = 'Network timeout';
        break;
      case 505:
         = 'The request is not supported by the http version';
        break;
      default:
         = `Connection error${}`;
    }
  } else {
     = 'Connect to server failed';
  }
  return ();
  });

import Vue from ‘vue';
import axios from ‘axios';

get request

({
	method:'get',
	url:'xxxx',
	reponseType:'',//Relevant type	parems:{//Introduce ginseng	}
}).then(function(response){
	....
})

Post Request

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
}).then(function(res){

});

delete request

axios({
  method: 'delete',
  url: '/user/12345',
 //Input parameter 1: Mount it after the request parmes:{
 }
 //Input parameter 2: Mount it into the request body data{
}
}).then(function(res){

});

put request: Update the entire object resource

axios({
  method: 'put',
  url: '/user/12345',
 data{
}
}).then(function(res){

});

patch request: update the object's local resources

axios({
  method: 'patch',
  url: '/user/12345',
 data{
}
}).then(function(res){

});

Provide another way of writing after packaging:
(url[, config])
(url[, config])
(url[, data[, config]])
(url[, data[, config]])
(url[, data[, config]])

Concurrent requests

(iterable)
(callback)
function getUserAccount() {
return ('/user/12345');
}
function getUserPermissions() {
  return ('/user/12345/permissions');
}
//Request array([getUserAccount(), getUserPermissions()])
  .then((function (acct, perms) {//Response body of the corresponding request    // Both requests are now completed  }));

What is the difference between axios and ajax?

axios:

Create http request from

Support Promise API

Client support to prevent CSRF

Provides some concurrent request interfaces (important, convenient for a lot of operations)

ajax:

The whole project is too big, and it is very unreasonable to simply use ajax to introduce the entire JQuery (it is not possible to enjoy CDN services if you adopt a personalized package solution)

How to customize the encapsulation of axios?

1. Establish basic configuration files such as interface request encapsulation, response, interception, authentication, etc.

Introducing static resources
import axios from 'axios';
 import qs from 'qs';
import apiMap from './apiMap';

Set global default parameters
 = false;
['Content-Type'] = 'application/json;charset=UTF-8';

Set the request default parameters
const instance = ({
    baseURL: .API_ROOT,
    timeout: 15 * 1000,
    auth: {
    	...
    },
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'X-Requested-With': 'XMLHttpRequest',
    },
  },
);
Set up request interception:
(function (config) {
...
})
Set up corresponding interception:
// Response interceptor is exception handling(response =&gt;
   response
, (err) =&gt; {
  if (err &amp;&amp; ) {
    switch () {
      case 400:
         = 'Bad Request';
        break;
      case 401:
         = 'Not authorized, please log in again';
        break;
      case 403:
         = 'access denied';
        break;
      case 404:
         = 'Request error, the resource was not found';
        break;
      case 405:
         = 'Request method is not allowed';
        break;
      case 408:
         = 'Request timed out';
        break;
       case 415:
         = 'The server cannot process the media format that comes with the request';
        break;
      case 500:
         = 'The server error';
        break;
      case 501:
         = 'Network not implemented';
        break;
      case 502:
         = 'Network Error';
        break;
      case 503:
         = 'Service is not available';
        break;
      case 504:
         = 'Network timeout';
        break;
      case 505:
         = 'The request is not supported by the http version';
        break;
      default:
         = `Connection error${}`;
    }
  } else {
     = 'Connect to server failed';
  }
  return ();
});
Encapsulation interface request:
let api={
	/**
	
	 * get method encapsulation
	
	 * @param url
	
	 * @param params
	
	 * @returns {Promise}
	
	 */
	
	get (url, params = {}) {
	  return new Promise((resolve, reject) =&gt; {
		  (apiMap[url],params).then(res =&gt; {
	      resolve()
	    }).catch(err =&gt; {
	      reject(err)
	    })
	  })
	},
	
	/**
	
	* post
	
	* @param url
	
	* @param params
	
	* @returns {Promise}
	
	*/
	
	post (url, params = {}) {
	  return new Promise((resolve, reject) =&gt; {
	    (apiMap[url], params)
	      .then(res =&gt; {
	        resolve()
	      }, err =&gt; {
	        reject(err)
	      })
	  })
	},
	
	/**
	
	 * delete method encapsulation
	
	 * @param url
	
	 * @param params
	
	 * @returns {Promise}
	
	 */
	
	delete (url, params = {}) {
	  return new Promise((resolve, reject) =&gt; {
	    (apiMap[url] ,params).then(res =&gt; {
	      resolve()
	    }).catch(err =&gt; {
	      reject(err)
	    })
	  })
	},
	
	/**
	
	 * put method encapsulation
	
	 * @param url
	
	 * @param params
	
	 * @returns {Promise}
	
	 */
	
	put (url, params = {}) {
	  return new Promise((resolve, reject) =&gt; {
	    (apiMap[url], params).then(res =&gt; {
	      resolve()
	    }).catch(err =&gt; {
	      reject(err)
	    })
	  })
	},
	
	/**
	
	 * patch method encapsulation
	
	 * @param url
	
	 * @param params
	
	 * @returns {Promise}
	
	 */
	
	patch (url, params = {}) {
	  return new Promise((resolve, reject) =&gt; {
	    (apiMap[url], params).then(res =&gt; {
	      resolve()
	    }).catch(err =&gt; {
	      reject(err)
	    })
	  })
	}
}

export default api;

2. Create a key-value interface file to facilitate interface request management

export default {
  // Topic List  key: 'path'
};

3. Introduce the index file into the vue entry file

Introducedvueresource
import Vue from 'vue'
IntroducedviewuiPlugin
import ViewUI from 'view-design';
Introducedviewuicssdocument
import 'view-design/dist/styles/';
导入document|默认不需要加document后缀
import Api from '/index';
Global binding|$ Set scope for instance properties
.$api = Api;

Global parameter configuration:

Create a configuration file:
import Vue from 'vue';
import Vuex from 'vuex';
import State from './state';
(Vuex);
const store = new (State);
export default store;
Create global parameter details file
export default {
	state: {   //Put the global parameters here		test: 0
	},
	mutations:{   //Set the value		test(state,value)=&gt;=value;
	},
	getters:{//Return value		test: state =&gt;;
	}
};
Call method:
var data = this.$;
var data = this.$('test',data);

(Vuex);

Determine whether vue has registered vuex plug-in;

Mix the vuexInit function into the vue's beforeCreate lifecycle;

When instantiating vue, the s t o re e attribute will be added to each instance of vue, and the instance of vue x will be bound to the store attribute, and the instance of vuex will be bound to the

to the store property and bind the instance of vuex to the store property.

Summarize

This is the end of this article about Vue applications encapsulated based on axios requests. For more related contents of axios requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!