Introduction of axios in Vue project

Posted by Imad on Sat, 18 Jan 2020 17:44:33 +0100

axios introduction

axios official website : easy to use, concise and efficient http library. axios official website

The core of axios is a promise based HTTP library, which can be used in browsers and node.js.

Characteristics of axios

  • Create XMLHttpRequests from the browser
  • Create http request from node.js
  • Support Promise API
  • Intercept requests and responses
  • Transform request data and response data
  • Cancellation request
  • Automatically convert JSON data
  • Client supports XSRF defense

Use of axios

Introduction of axios

yarn add axios;
npm install axios;
<script src="https://unpkg.com/axios/dist/axios.min.js" defer />

axios example

yarn add axios;
npm install axios;
<script src="https://unpkg.com/axios/dist/axios.min.js" />
// Use
axios.get('/config?id=123')
  .then(res => {
  	console.log(res);
  })
axios.post('/config', {id: 123})
  .then(res => {
  	console.log(res);
  })
axios({
  method: 'post',
  url: '/config',
  data: {
    id: 123
  }
})

options content of axios

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

  // `Method 'is the method used to create a request
  method: 'get', // default

  // `baseURL will be automatically added before 'url', unless' url 'is an absolute url.
  // It can easily pass the relative URL for axios instance by setting a 'baseURL'
  baseURL: 'https://some-domain.com/api/',

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

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

  // `Headers are the custom request headers 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: {
    ID: 12345
  },

   // `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 for 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 the request times out (0 means no timeout)
  // If the requested call takes longer than 'timeout', the request will be interrupted
  timeout: 1000,

   // `With credentials' 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 (refer to [response docs] (ාresponse API))
  adapter: function (config) {
    /* ... */
  },

 // `auth 'means HTTP basic authentication should be used and credentials should be provided
  // This will set an 'Authorization' header and overwrite the existing custom 'Authorization' header set by using 'headers' arbitrarily
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

   // `responseType 'indicates the data type of 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

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

   // `onUploadProgress' allows processing 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 response content allowed
  maxContentLength: 2000,

  // `validateStatus' defines whether the status code of a given HTTP response is resolve or reject project. If 'validateStatus' returns' true' (or is set to 'null' or 'undefined'), the project will be resolved; otherwise, the project will be rejecte d
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects' defines the maximum number of redirects to follow in node.js
  // If set to 0, no redirection will follow
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' 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 respectively used in node.js to define the custom agent 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 broker and provide credentials
  // This will set a 'proxy authorization' header and overwrite the existing custom 'proxy authorization' header set by using 'header'.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

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

Content of axios' res

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

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

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

  // `Headers' the headers of the server response
  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 node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

Vue plug-in use

Using plug-ins through the global method Vue.use(plugin)

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

Use of axios in Vue

axios cannot mount the global plug-in through Vue.use

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

Vue.use(axios);// TypeError

axios needs to be mounted on Vue.prototype to mount global variables

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

Vue.prototype.$axios = axios;
// You can call this.$axios in the Vue instance
this.$axios(url, options);

Using Vue Axios plug-in to mount the global plug-in through Vue.use

import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);
// Use
Vue.axios.get(api).then((response) => {
  console.log(response.data)
});

this.axios.get(api).then((response) => {
  console.log(response.data)
});

this.$http.get(api).then((response) => {
  console.log(response.data)
});

Using Vue Axios plugin to mount global plugins through Vue.use

import Vue from 'Vue';
import VueAxiosPlugin from 'vue-axios-plugin';

Vue.use(VueAxiosPlugin, {
  // Request interception processing
  reqHandleFunc: config => config,
  reqErrorFunc: error => Promise.reject(error),
  // Response interception processing
  resHandleFunc: response => response,
  resErrorFunc: error => Promise.reject(error)
});
// Use
this.$http.get(url, data, options).then((response) => {
  console.log(response)
});
this.$http.post(url, data, options).then((response) => {
  console.log(response)
});
this.$axios.get(url, data, options).then((response) => {
  console.log(response)
});
this.$axios.post(url, data, options).then((response) => {
  console.log(response)
});
Published 40 original articles, won praise 3, 10000 visitors+
Private letter follow

Topics: axios Vue JSON npm