Packaging and use of Vue Axios

catalogue

Axios description

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

install

Installation in npm

npm install axios

Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios request configuration

The following are all configuration items that can be set during the request. Only the url is required. If it is not specified, the request will be made in the get mode by default.

{
  // `URL ` is the server URL for the request
  url: '/user',

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

  // `baseURL 'will be automatically added before' URL ', unless' URL' is an absolute URL.
  // It can set a 'baseURL' to facilitate the delivery of relative URL s for axios instance methods
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest ` allows you to modify the request data before sending it to the server
  // It can only be used in the request methods of 'PUT', 'POST' and 'PATCH'
  // The function in the following array must return a string, or ArrayBuffer, or Stream
  transformRequest: [function (data) {
    // Arbitrary conversion of data
    return data;
  }],

  // `transformResponse ` it is allowed to modify the response data before passing it to then/catch
  transformResponse: [function (data) {
    // Arbitrary conversion of data
    return data;
  }],

  // `headers ` is the custom request header to be sent
  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: {
    userId: 1
  },

  // `paramsSerializer ` is a function responsible for 'params' serialization
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `Data ` is the data sent as the request body
  // Only applicable 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 specific: FormData, File, Blob
  // -Node exclusive: Stream
  data: {
    userName: 'levy'
  },

  // `Timeout ` specifies the number of milliseconds the request times out (0 means no timeout)
  // If the call cost exceeds the 'timeout', the request will be interrupted
  timeout: 1000,

  // `withCredentials ` indicates whether credentials are required for cross domain requests
  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 ` indicates that HTTP basic authentication should be used and credentials should be provided
  // This will set an 'Authorization' header, overwriting any existing custom 'Authorization' header set with 'headers'
  auth: {
      username: 'levy',
      password: '123456'
  },

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

  // `Xsrfcookie name ` 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 value of xsrf token
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

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

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

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

  // `The status of the given project is the status of the HTTP response defined as' revalidate 'or' resolve '.
  //If 'validateStatus' returns' true' (or set to 'null' or 'undefined'), promise will be resolve d; Otherwise, project will be rejecte d
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects ` is defined in node The maximum number of redirects of follow in JS
  // If set to 0, no redirection will follow
  maxRedirects: 5, // default

  // `httpAgent 'and' httpsAgent 'are on node JS is used to define the custom proxy used when executing http and https. Allow options to be configured like this:
  // `keepAlive ` is not enabled by default
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the host name and port of the proxy server
  // `auth ` indicates 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 by using 'header'.
  proxy: {
    host: '127.0.0.1',
    port: 8080,
    auth: : {
      username: 'levy',
      password: '123456'
    }
  },

  // `cancelToken ` specifies the cancel token used to cancel the request
  // (see the Cancellation section later for more information)
  cancelToken: new CancelToken(function (cancel) {
  })
}

Response structure

The general request response structure is as follows:

{
  // `data ` response provided by the server
  data: {},

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

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

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

  // `config ` is the configuration information provided for the request
  config: {}
}

Common request methods

When using axios, you can use the following methods as long as axios is referenced in the current operation form,
Or axios is introduced globally.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

Default value configuration

In the program request, there must be multiple requests, and some configurations are fixed and the same by default

Global request configuration item

Therefore, you can set the default value of global request configuration items, such as

axios.defaults.baseURL = 'https://api.example.com'
axios.defaults.headers.common['token'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

Custom instance defaults

// Set the default value of the configuration when creating an instance
var instance = axios.create({
    baseURL: 'https://api.example.com',
})

// Modify the default value after the instance has been created
instance.defaults.headers.common['token'] = AUTH_TOKEN

Priority of configuration

Configurations are merged in one order of priority. The order is: in lib / defaults JS, then the defaults attribute of the instance, and finally the config parameter of the request. The latter will take precedence over the former.

Here is just an example written in terms of timeout (the same setting method as other configuration items):

// Create an instance using the default values of the configuration provided by the library
// At this time, the default value of timeout configuration is ` 0`
var instance = axios.create()

// Override the default timeout value of the library during global configuration
// Now, all requests will wait 2.5 seconds before timeout
instance.defaults.timeout = 2500

// Override the timeout setting for a request that is known to take a long time in a single request
instance.get('/longRequest', {
    timeout: 5000,
})

Interceptor

Intercept requests or responses before they are processed by then or catch.

// Add request interceptor
axios.interceptors.request.use(
    function (config) {
        // What to do before sending the request
        return config
    },
    function (error) {
        // What to do about request errors
        return Promise.reject(error)
    }
)

// Add response interceptor
axios.interceptors.response.use(
    function (response) {
        // Do something about the response data
        return response
    },
    function (error) {
        // Do something about response errors
        return Promise.reject(error)
    }
)

If you want to remove the interceptor later, you can do this:

var myInterceptor = axios.interceptors.request.use(function () {
    /*...*/
})
axios.interceptors.request.eject(myInterceptor)

You can add interceptors for custom axios instances

var instance = axios.create()
instance.interceptors.request.use(function () {
    /*...*/
})

Personal complete axios configuration

Create a new folder to manage the global default configuration config. Of axios JS items are as follows:

The following baseurl can be found in env.production and env. Add the corresponding parameters to development, and then use process env. baseUrl

It needs special attention env.production and env. Description of development file parameters:

  • NODE_ENV - is "development", "production", "test" or a custom value. The specific value depends on the running mode of the application
  • BASE_URL - and Vue config. The publicPath option in JS matches, that is, the basic path to which your application will be deployed
  • Except NODEENV and BASE_URL, other environment variables must be in VUE_APP start
  • Used in the project: process env. Environment variable name, eg: VUE_APP_BASE_URL
const urlMap = {
    development: 'http://localhost:5000/',
    production: '', //Online environment IP address
}
const baseUrl = urlMap[process.env.NODE_ENV]
export default {
    method: 'get',
    // Base url prefix
    baseURL: baseUrl,
    // Request header information
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
    // parameter
    data: {},
    // Set timeout
    timeout: 10000,
    // Return data type
    responseType: 'json',
}

Then create a new axios configuration file, axioshttp js.

import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import config from './config'

axios.defaults.timeout = config.timeout
axios.defaults.headers = config.headers
axios.defaults.baseURL = config.baseURL

// request interceptor 
axios.interceptors.request.use(
    (config) => {
        // Trigger loading effect
        //If the token exists, add the token to determine whether the token exists
        // let token = getStore('token')
        // if (token) {
        //     config.headers.common['token'] = token
        // }
        // if (config.method == 'post' || config.method == 'put') {
        //     //Convert data to string
        //     config.data = JSON.stringify(config.data)
        // } else if (config.method == 'get') {
        //     //&& browser.isIE
        //     //Add timestamp to Get to solve IE cache problem
        //     let symbol = config.url.indexOf('?') >= 0 ? '&' : '?'
        //     config.url += symbol + '_=' + Date.now()
        //     config.data = qs.stringify(config.data)
        // }
        return config
    },
    (err) => {
        // Close loading
        // Failure prompt
        return Promise.resolve(err)
    }
)

// Response interceptor
axios.interceptors.response.use(
    (response) => {
        // Close loading
        if (!response || !response.data || !response.data.success) {
            // Failure prompt
        } else if (response.data.data && response.data.code == 200) {
            // Successfully processed
        }
        if (response.data) {
            switch (response.data.code) {
                case 401:
                    // Return to 401, clear the token information and jump to the login page
                    // store.commit('LOGOUT')
                    setTimeout(function () {
                        router.replace({
                            path: '/login',
                            // After successful login, jump to the current page
                            // query: {redirect: router.currentRoute.fullPath}
                        })
                    }, 1500)
                    break
                case 402:
                    //402 operation without permission
                    // Tips
                    return new Promise(() => {}) //External will not be processed
                    break
            }
        }
        return response
    },
    (err) => {
        // Close loading
        // Prompt exception
        // return Promise.resolve(err);
        //External will not be processed
        return new Promise(() => {})
    }
)
export default {
    Get(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios
                .get(url, { params })
                .then((res) => {
                    resolve(res.data)
                })
                .catch((error) => {
                    reject(error)
                    //resolve(error)
                })
        })
    },
    Post(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios
                .post(url, params)
                .then((res) => {
                    resolve(res.data)
                })
                .catch((error) => {
                    reject(error)
                    //resolve(error)
                })
        })
    },
    Delete(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios
                .delete(url, params)
                .then((res) => {
                    resolve(res.data)
                })
                .catch((error) => {
                    reject(error)
                    //resolve(error)
                })
        })
    },
    Put(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios
                .put(url, params)
                .then((res) => {
                    resolve(res.data)
                })
                .catch((error) => {
                    reject(error)
                    //resolve(error)
                })
        })
    },
}

Introduce axioshttp in each module JS file, directly use the method inside, and capitalize the first character.

Import each module in the API file, in main Mount the API of vue to the attribute of VJs. The call on the page is this$ api. methodName

Original address: http://book.levy.net.cn/doc/frontend/axios.html

Tags: Vue

Posted by Pjack125 on Sat, 21 May 2022 16:49:45 +0300