Axios is a Promise-based HTTP library that can be used in browsers and Node.js. www.axios-js.com/zh-cn/docs/ Github address: github.com/axios/axios…

1. Install

npm install axios --save
or
yarn add axios
Copy the code

2. Use

Axios provides method aliases. You can also use the AXIos object +config directly to determine the request type and pass parameters. The method aliases are just a wrapper around AXIos

2.1 axios(config), axios(url, [config])

The request can be created by passing the relevant configuration to AXIOS. The detailed configuration of config can be seen in 3. In addition to individual attributes, request types (GET, POST, PUT, delete) are distinguished.

import axios from 'axios';

import qs from 'qs';
// Send a POST request with data as the parameter
axios({
    method: 'post'.url: '/add'.data: {
        name: 'zgm'.age: 17}});// Send the get request, pass the parameter with params
axios({
    method: 'get'.url: '/getList'.params: {
        name: 'zgm'.age: 17    
    },
    // Serialize params parameters - [optional]
    paramsSerializer: function(params) {
        return qs.stringify(params, {arrayFormat: 'brackets'})}});Copy the code

2.2 axios. Get axios. Post

Axios provides aliases 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]])
Copy the code

Note: 1. The config configuration is the same as that in 3. 2. The post, PUT, patch request extracts data from the parameter list. You can also set config.data to add request parameters.

import axios from 'axios';

axios.get('/getList', {params: {
        name: 'zgm'.age: 17 
    },
    responseType: 'json'.timeout: 1000,
})

axios.post('/getList',data, {
    responseType: 'json'.timeout: 1000,})Copy the code

3. Global configuration

3.1 Default Global Configuration

Configuration anywhere in the project takes effect globally!

import axios from 'axios';

axios.defaults.baseURL = '/baseurl' // Configure the address requested by Axios
axios.defaults.headers.post['Content-Type'] 
                                    = 'application/json; charset=utf-8';
axios.defaults.crossDomain = true;
axios.defaults.withCredentials = true;  // Set cross to allow cookie information to be carried across domains
Copy the code

3.2 Customizing Example Default Configuration

import axios from 'axios';

const instance = axios.create({
    baseURL: '/baseurl'    
})// The configuration is the same as that in 4

instance.defaults.baseURL = '/baseurl' // Configure the requested base address
Copy the code

3.3 Global interceptor

Request interceptors and response interceptors can be added for the request global

//axios-init.js
import axios from "axios";

// Configure the interceptor before sending the request to set the token information
axios.interceptors.request.use(
  (config) = > {
    // Configure global loading
    if (!/\.json/.test(config.url)) {
      $("#screen").show(); // This div controls loading animation. There is a request for JSON in the project, so it is not a JSON file
    }
    return config;
  },
  (error) = > {
    return Promise.reject(error); });// Configure the response interceptor
axios.interceptors.response.use(
  (res) = >{$("#screen").hide(); / / end of loading
    return Promise.resolve(res.data); // Return data directly, that is, all the data returned by the interface
  },
  (error) = >{$("#screen").hide();
    tooltip(""."Wrong connection!"."error");
    // Determine whether the login is invalid based on the interface status of the actual project
    if (error.toString().includes("776")) {
      window.location.href = window.location.origin + "/#/login";
    }
    return Promise.reject(error); });export default axios;
Copy the code

4. Complete the Config configuration

See the official website: www.axios-js.com/zh-cn/docs/…

{
  // '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/".// '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.// '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. }Copy the code