Procedure for configuring axios Based on vue
About axios
Axios is an HTTP client based on Promise for browsers and nodejs. It has the following features:
- Create XMLHttpRequest from the browser
- Send http requests from node. js
- Support Promise API
- Intercept requests and responses
- Convert request and Response Data
- Cancel request
- Automatic JSON Data Conversion
- Client Support prevents CSRF/XSRF
1. Background
- In project development, ajax requests are indispensable
- Some ajax requests do not need to be loading, or the request time is less than a certain number, so the loading is not displayed.
- Unified request processing in the project (error processing, returned data formatting, loading processing, and token processing)
- Configuration is based on a personal vue project. vux-related components have been loaded, and some dependent import operations are performed (you can configure as needed)
Import Vue from 'vue 'import axios from 'axios' // some environment configuration parameters of the project, read hostimport config from '@/config' // vuex status management, here we mainly control the global loading. import store from '@/store' // vue-router page operations on the corresponding status code (router instance) import router from '@/router' // The console encapsulates import {log} from '@/utils'
2. Solutions
In the axios encapsulation, we define several parameters for declaration.
// Load minimum time const MINI_TIME = 300 // timeout (timeout) let TIME_OUT_MAX = 5000 // environment valuelet _ env = process. env. NODE_ENV // request the hostlet _ apiHost = config. api // request group (determining the current number of requests) let _ requests = []
Generally, the root host and Content-Type of a project are unified, configure axios in a unified way. (If the backend needs a formData form, that is, content-type = 'application/x-www-form-urlencoded; charset = UTF-8, form serialization is required for request data. The quick method is to introduce the qs library qs. stringify for post-processing transmission)
axios.defaults.headers.common['Content-Type'] = 'application/json'axios.defaults.baseURL = _apiHost
Under normal circumstances, more than one request is ongoing (not yet returned) at the same time in the project. To determine whether there is still ongoing ajax, you need to maintain the _ requests array;
/*** Add the request and display loading * @ param {request configuration} config */function pushRequest (config) {log ('$ {config. url} -- begin ') _ requests. push (config) Vue. $ vux. loading. show ({text: 'loading'}) store. dispatch ('loading')}/*** remove request. If no request exists, close loading * @ param {request configuration} config */function popRequest (config) {log ('$ {config. url} -- end') let _ index = _ requests. findIndex (r => {return r = config}) if (_ index>-1) {_ requests. splice (_ Index, 1)} if (! _ Requests. length) {Vue. $ vux. loading. hide (0) store. dispatch ('loading', false )}}
Next, process axios based on the above preparations.
/*** Request address, request data, silent or not, Request method */export default (url, data ={}, isSilence = false, method = 'post ') ==>{ let _ opts = {method, url} // combine common data (token) let _ data = Object. assign ({}, data, {token: store. getters. token}) const _ query ={}for (let _ key in _ data) {if (_ data. hasOwnProperty (_ key) & _ data [_ key]! = '') {_ Query [_ key] = _ data [_ key]} // request timer ID let _ timer = null for the axios instance // determine the request type if (method. toLocaleUpperCase () === 'post') {_ opts. data = _ query} else {_ opts. params = _ query} // return a promise return new Promise (resolve, reject) =>{// instantiate axios const _ instance = axios. create ({timeout: TIME_OUT_MAX}) // defines the unique identifier of the request, let _ random = {stamp: Date. now (), url: '$ {_ apiHost + url}'} // determines whether the request is silent (if it is silent, the request mark is not added. Recognition queue. if (! IsSilence) {_ timer = setTimeout () => {pushRequest (_ random)}, MINI_TIME)} // The axios instance sends the current request // The request is complete: 1. Cancel the timer of the current request. 2. Remove the current ID from the current request ID queue;
3. If the operation succeeds, the data after unified processing is returned. If the operation fails, the status code is determined.
_ Instance (_ opts ). then (res => {let responseData = res. data clearTimeout (_ timer) popRequest (_ random) resolve (res. data )}). catch (res => {let _ response = res. response let _ message = null clearTimeout (_ timer) popRequest (_ random) switch (_ response. status) {case 404: _ message = '100, error request 'break case 404: router. push ({path: '/login', query: {redirect: router. currentRoute. fullPath}) _ message = 'unauthorized Authority 'break case 403: _ message = 'Access prohibited 'break case 408: _ message = 'request timeout' break case 500: _ message = 'internal server error' break case 501: _ message = 'function not implemented 'break case 503: _ message =' service unavailable 'break case 504: _ message = 'Gateway error' break default: _ message = 'unknown error'} if (! IsSilence) {Vue. $ vux. toast. show ({text: _ response. data & _ response. data. error? _ Response. data. error: _ message, type: 'warn', width: '10em '})} reject (res )})})}
Github address: https://github.com/NoManReady/Tide/blob/master/src/utils/fetch.js
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.