Introduction to axios
axios is an HTTP client based on Promise for browsers and nodejs, which itself has the following characteristics:
- Create XMLHttpRequest from the browser
- Make an http request from
- Support Promise API
- Intercept requests and responses
- Convert request and response data
- Cancel request
- Automatically convert JSON data
- Client support to prevent CSRF/XSRF
1. Background
- ajax request is indispensable in project development
- Some ajax requests do not require loading or the request time is less than that, loading will not be displayed.
- The same processing of requests in the project (Error processing, return data formatting processing, loading processing, token processing)
- The configuration is configured based on personal vue projects. Vux-related components have been loaded and some dependencies will be implemented (can be configured on demand)
import Vue from 'vue' import axios from 'axios' // Some environment configuration parameters of the project, read hostimport config from '@/config' //vuex state management, where the control of global loading is mainly carried outimport store from '@/store' //vue-router's page operation on the corresponding status code (router instance)import router from '@/router' //Console corresponding packageimport { log } from '@/utils'
2. Solution
For axios package, we define several parameters to declare
// Minimum loading timeconst MINI_TIME = 300 // Timeout time (timeout time)let TIME_OUT_MAX = 5000 // Environment valuelet _env = .NODE_ENV // Request interface hostlet _apiHost = // Request group (judgment the current number of requests)let _requests = []
Generally, the root host and Content-Type in a project are unified, so axios is configured uniformly (if this backend requires formData format, i.e. content-type='application/x-www-form-urlencoded;charset=utf-8' data, and the requested data needs to be serialized. The faster way is to introduce the qs library for processing and transmission)
['Content-Type'] = 'application/json' = _apiHost
Generally, there will be more than one request in the project at the same time (has not returned yet). To determine whether there is still ajax in progress, the _requests array needs to be maintained;
/** * Add a request to display loading * @param {request configuration} config */ function pushRequest(config) { log(`${}--begin`) _requests.push(config) Vue.$({ text: 'Loading' }) ('loading') } /** * Remove the request and close loading if there is no request * @param {request configuration} config */ function popRequest(config) { log(`${}--end`) let _index = _requests.findIndex(r => { return r === config }) if (_index > -1) { _requests.splice(_index, 1) } if (!_requests.length) { Vue.$(0) ('loading', false) } }
Next, axios is processed based on the above preparation
/** * Request address, request data, whether it is silent, request method */ export default (url, data = {}, isSilence = false, method = 'POST') => { let _opts = { method, url } //Token of general data let _data = ({}, data, { token: }) const _query = {} for (let _key in _data) { if (_data.hasOwnProperty(_key) && _data[_key] !== '') { _query[_key] = _data[_key] } } // Axios instance request timer ID let _timer = null //Judge request type if (() === 'POST') { _opts.data = _query } else { _opts.params = _query } //Return a promise return new Promise((resolve, reject) => { //Instantiate axios const _instance = ({ timeout: TIME_OUT_MAX }) //Define the unique identifier of the request let _random = { stamp: (), url: `${_apiHost + url}` } //Judge whether it is silent (if it is silent, it will not be added to the request identification queue, otherwise it will declare the timer for this request instance) if (!isSilence) { _timer = setTimeout(() => { pushRequest(_random) }, MINI_TIME) } // Axios instance sends the current request //Request completion: 1. Cancel the timer for the current request; 2. Remove the current identifier from the current request identification queue;
3. If successful, return the data after unified processing. If the status code fails, judge the status code.
_instance(_opts) .then(res => { let responseData = clearTimeout(_timer) popRequest(_random) resolve() }) .catch(res => { let _response = let _message = null clearTimeout(_timer) popRequest(_random) switch (_response.status) { case 404: _message = '404, erroneous request' break case 401: ({ path: '/login', query: { redirect: } }) _message = 'Unauthorized' break case 403: _message = 'No access' break case 408: _message = 'Request timed out' break case 500: _message = 'Internal Server Error' break case 501: _message = 'Function not implemented' break case 503: _message = 'Service is not available' break case 504: _message = 'Gateway Error' break default: _message = 'Unknown Error' } if (!isSilence) { Vue.$({ text: _response.data && _response. ? _response. : _message, type: 'warn', width: '10em' }) } reject(res) }) }) }
Github address:/NoManReady/Tide/blob/master/src/utils/
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.