1 Axios Chinese document

What is Axios?

Axios is a Promise-based HTTP library that can be used in browsers and Node.js.

axios

Axios is a Promise-based HTTP library that can be used in browsers and Node.js.

features

  • Create XMLHttpRequests from the browser
  • Create HTTP requests from Node.js
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request data and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports XSRF defense

Browser support

Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 8 + ✔

The installation

Using NPM: Using Bower:

npm install axios
Copy the code
bower install axios
Copy the code

Use the CDN:

case

Performing a GET request

// Create a request for the user with the given ID
axios.get('/user? ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// The above request can also do the same
axios.get('/user', {
    params: {
      ID: 12345
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);  
});
Copy the code

Performing a POST request

axios.post('/user', {
    firstName: 'Fred'.lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy the code

Execute multiple concurrent requests

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now completed
}));
Copy the code

axios API

The request can be created by passing the relevant configuration to AXIOS

axios(config)
// Send a POST request
axios({
  method: 'post'.url: '/user/12345'.data: {
    firstName: 'Fred'.lastName: 'Flintstone'}});Copy the code
// Get the remote image
axios({
  method:'get'.url:'http://bit.ly/2mTM3nY'.responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});Copy the code

axios(url[, config])
// Send a GET request (default method)
axios('/user/12345');
Copy the code

Alias of the request method

Aliases are provided for all supported request methods for convenience

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

Pay attention to

When alias methods are used, the URL, method, and data attributes do not have to be specified in the configuration.

concurrent

Helper functions that handle concurrent requests

axios.all(iterable)

axios.spread(callback)

Create an instance

You can create a new AXIOS instance using a custom configuration

axios.create([config])
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/'.timeout: 1000.headers: {'X-Custom-Header': 'foobar'}});Copy the code

Instance methods

The following example methods are available. The specified configuration is merged with the configuration of the instance.

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

Request configuration

These are the configuration options you can use when creating a request. Only urls are required. If method is not specified, the request uses the get method by default.

{
   // 'url' is the server URL used for the request
  url: '/user'.// 'method' is the method used to create the request
  method: 'get'.// default

  // baseURL will automatically precede url unless the url is an absolute URL.
  // It can facilitate passing relative urls to axios instance methods by setting a 'baseURL'
  baseURL: 'https://some-domain.com/api/'.// 'transformRequest' allows request data to be modified before being sent to the server
  // Only for 'PUT', 'POST', and 'PATCH' request methods
  // The function in the following array must return a string, either an ArrayBuffer, or a Stream
  transformRequest: [function (data, headers) {
    // Perform any conversion on data
    returndata; }].// 'transformResponse' allows the response data to be modified before being passed to then/catch
  transformResponse: [function (data) {
    // Perform any conversion on data
    returndata; }].// 'headers' is a 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: {
    ID: 12345
  },

   // 'paramsSerializer' is a function that serializes' params'
  // (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 that is sent as the body of the request
  // Apply 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 specific: FormData, File, Blob
  // - Node exclusive: Stream
  data: {
    firstName: 'Fred'
  },

  // 'timeout' specifies the number of milliseconds for the request to timeout (0 indicates no timeout)
  // If the request takes longer than timeout, the request will be interrupted
  timeout: 1000.// 'withCredentials' indicates whether credentials are needed for cross-domain requests
  withCredentials: false.// default

  // Adapter allows you to customize handling 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 base authentication should be used and credentials provided
  // This will set an Authorization header that overrides any existing custom Authorization header set using headers
  auth: {
    username: 'janedoe'.password: 's00pers3cret'
  },

   // 'responseType' indicates 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 the 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 progress events to be processed for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // 'onDownloadProgress' allows progress events to be processed for downloads
  onDownloadProgress: function (progressEvent) {
    // Handling of native progress events
  },

   // 'maxContentLength' defines the maximum size allowed for response content
  maxContentLength: 2000.// 'validateStatus' defines a resolve or reject PROMISE for a given HTTP response status code. If 'validateStatus' returns' true' (or is set to 'null' or 'undefined'), promises will be resolved; Otherwise, the promise will be rejecte
  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 be followed
  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 used in Node.js to define custom agents to be used when performing HTTP and HTTPS, respectively. Allow configuration options like this:
  // keepAlive is disabled 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 to connect to the 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: 9000.auth: {
      username: 'mikeymike'.password: 'rapunz3l'}},// 'cancelToken' specifies the cancel token used to cancel the request
  // (See the Cancellation section later for more information)
    
  cancelToken: new CancelToken(function (cancel) {})}Copy the code

Response of the structure

The response to a request contains the following information

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

  // 'status' is the HTTP status code from the server response
  status: 200.// 'statusText' is the HTTP status information from the server response
  statusText: 'OK'.// 'headers' is the head 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: {}
}
Copy the code

When you use then, you receive the following response:

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
});
Copy the code

When a catch is used, or when a Rejection callback is passed as the second argument to a THEN, the response can be used via an error object, as we see in the error handling section.

Configure default Values

You can specify configuration defaults that will be used on individual requests

The global AXIOS default value

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Copy the code

Custom instance defaults

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Copy the code

Configuration priority

Configurations are merged in a priority order. The order is: the library defaults found in lib/defaults.js, then the instance defaults property, and finally the requested Config parameters. The latter will take precedence over the former. Here’s an example:

// Create the instance using the default values of the configuration provided by the library
// The default value of the timeout configuration is 0
var instance = axios.create();

// Override library timeout default value
// Now all requests wait 2.5 seconds before timeout
instance.defaults.timeout = 2500;

// Set override timeout for requests known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});
Copy the code

The interceptor

Intercepts 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 the request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // What to do with the response data
    return response;
  }, function (error) {
    // Do something about the response error
    return Promise.reject(error);
  });
Copy the code

If you want to remove interceptors later, you can do this:

const myInterceptor = axios.interceptors.request.use(function () {/ *... * /});
axios.interceptors.request.eject(myInterceptor);
Copy the code

You can add interceptors for custom AXIOS instances

const instance = axios.create();
instance.interceptors.request.use(function () {/ *... * /});
Copy the code

Error handling

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
Copy the code

Y you can use the validateStatus configuration option to define an error range for a custom HTTP status code.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500}})Copy the code

cancel

Cancel the request using the Cancel token

Axios’ Cancel Token API, based on Cancelable Promises Proposal, is in its first phase.

The cancel token can be created using the canceltoken. source factory method like this:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
     // Processing error}}); axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// Cancel the request (the message argument is optional)
source.cancel('Operation canceled by the user.');
Copy the code

CancelToken can also be created by passing an executor function to the CancelToken constructor:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // The executor function takes a cancel function as an argumentcancel = c; })});// cancel the request
cancel();
Copy the code

Note: You can cancel multiple requests using the same Cancel token

Use the application/x – WWW – form – urlencoded format

By default, AXIos serializes JavaScript objects into JSON. To send data in Application/X-www-form-urlencoded format, you can use one of the following options.

The browser

In a browser, you can use the URLSearchParams API as follows:

const params = new URLSearchParams();
params.append('param1'.'value1');
params.append('param2'.'value2');
axios.post('/foo', params);
Copy the code

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but polyfill (be sure to populate the global environment) can be used.

Alternatively, you can use the QS library to encode data:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
Copy the code

Or in another way (ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST'.headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);
Copy the code

Node.js

In Node.js, you can use the QueryString module, as follows:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
Copy the code

You can also use the QS library.

Semver

Until Axios reaches version 1.0, the disruptive changes will be released in a new minor version. For example, 0.5.1 and 0.5.4 will have the same API, but 0.6.0 will have major changes.

Promises

Axios relies on the native ES6 Promise implementation to be supported. If your environment doesn’t support ES6 Promises, you can use Polyfill. ##3 TypeScript Axios includes TypeScript definitions.

import axios from 'axios';
axios.get('/user? ID=12345');
Copy the code

resources

Credits

Axios is inspired by Angular’s $HTTP service. Finally, Axios provides a separate $HTTP-like service for use outside of Angular.

2. Application of AXIOS in the project

/** * HTTP configuration ** axios Parameter Description * isSerialize whether to enable form submission * isToken whether to require token */

import axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
import { serialize } from '@/util/util'
import {getToken,getRoleTitle} from '@/util/auth' // Obtain the corresponding permission
import {Message} from 'element-ui' // Call the popover component
import website from '@/config/website'; // statusWhiteList gets the whitelist by default [400]
import NProgress from 'nprogress' // Progress bar in vue
import 'nprogress/nprogress.css' // progress bar style
import Cookies from 'js-cookie'

axios.defaults.timeout = 20000; // Set the timeout period

// Return another state
// Define resolve or Reject PROMISE for a given HTTP response status code.
// If 'validateStatus' returns true (or is set to' null 'or' undefined '),
// Promise will be resolved; Otherwise, the promise will be rejecte

axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500; / / the default
};

// Cross-domain request, allow to save cookies
axios.defaults.withCredentials = true;

// NProgress Configuration
// Turn off the load spinner by setting it to false. (Default is true)
NProgress.configure({
    showSpinner: false
});

//HTTPrequest interceptor - Add request interceptor
axios.interceptors.request.use(config= > {
    
    NProgress.start() // start progress bar loader starts loading
    
    const meta = (config.meta || {}); // 
    
    const isToken = meta.isToken === false;
    
    if(getToken() && ! isToken) { config.headers['Admin.Authority.Token.cashloan'] = getToken();
        // 'Bearer '+ getToken() // Let each request carry token--['Authorization'] is a custom key please modify it according to actual situation
    }
    
    // Headers set serialize to true to enable or disable form submission
    if (config.methods === 'post' && meta.isSerialize === true) {
        config.data =config.data => {
            let list = [];
            Object.keys(data).forEach(ele= > {
                list.push(`${ele}=${data[ele]}`)})return list.join('&');
        };
    }
    
    return config
    
}, error => {
    return Promise.reject(error)
});

//HTTPresponse interceptor - Add a response interceptor
axios.interceptors.response.use(res= > {
    NProgress.done(); // The progress bar closes
    
    const status = Number(res.status) || 200; // Return value must be 200
    
    const statusWhiteList = website.statusWhiteList || []; // Whitelist 400
    
    const message = res.data.message || 'Unknown error'; // Return value for certain or 'unknown error'
   
    const code = res.data.code
    
    if (code === 11002) {
        Message({
            message,
            type: "error"})}if (code === 10004) {
        Message({
            message: "Another device logged in.".type: 'error'
        })
        store.dispatch('FedLogOut').then((a)= > router.push({
            path: '/login'
        }));
    }
    
    if (code === 10001) {
        Message({
            message: "Please log in again".type: 'error'
        })
        Cookies.set('loading'.true)
        store.dispatch('FedLogOut').then((a)= > router.push({
            path: '/login'
        }));
    }
    
    if (code === 10002) {
        Message({
            dangerouslyUseHTMLString: true.message: ` interface for${res.request.custom.url}</br></br>${getRoleTitle()}No permission '.type: 'error'})}if (code === 10003) {
        Message({
            dangerouslyUseHTMLString: true,
            message,
            type: 'error'})}if (code === 404) {
        Message({
            dangerouslyUseHTMLString: true.message: ` interface for${res.request.custom.url}</br></br>The ${JSON.stringify(res.data)}`.type: 'error'})}if (code === 400) {
        
        if (res.data.message.includes('/')) {
            Message({
                dangerouslyUseHTMLString: true.message: message.split('/') [1].type: 'error'
            })
            return
        }

        Message({
            dangerouslyUseHTMLString: true.message: `The ${JSON.stringify(res.data)}`.type: 'error'})}if (code === 500) {
        if(! res.data.message.includes("TIMEOUT")){
            Message({
                dangerouslyUseHTMLString: true.message:Server is down, please try again later./ / message: ` interface is ${res. Request. Custom. Url} < / br > < br / > ${JSON. Stringify (res) data)} `,
                type: 'error'}}})// If you are in the whitelist, catch logic
    if (statusWhiteList.includes(status)) return Promise.reject(res);
    // If 401, jump to the login page
    if (status === 401) store.dispatch('FedLogOut').then((a)= > router.push({ path: '/login' }));
    // If the request is not 200, no will be processed by default
    if(status ! = =200) {
        Message({
            message: message,
            type: 'error'
        })
        return Promise.reject(new Error(message))
    }
    return res;
}, error => {
    NProgress.done();
    return Promise.reject(new Error(error));
})

export default axios;
Copy the code