axios

To develop network requests, you can choose the following ways:

  • Ajax, XMLHttpRequest (XHR) based

    Configuration and invocation are too confusing, and coding is too complex

  • jQuery-Ajax

    While easier to use than traditional Ajax, there is no need to introduce jQuery to use Ajax in Vue development

  • Vue-resource

    Used only when Vue1. X is no longer maintained

  • Axios (Official recommendation!!) : ajax I/o system

    • XMLHttpRequests can be sent in the browser
    • Support for sending HTTP requests in Node.js
    • Supporting Promise API
    • Intercept requests and responses
    • Transform request and response data

The basic use

#The installation
npm install axios --save

#The import
import axios from 'axios'

#The basic use
axios({
  url: 'https://httpbin.org/headers',
  method: 'get'
}).then(res => {
  console.log(res);
})

#[Note] Httpbin.org is too slow for test requests to return data after several seconds
#Improt import is required at the beginning of any page that needs to use AXIos
Copy the code

Parameter concatenation

axios({
  url: 'http://xxx.com/page?'.params: {		// Params is a parameter concatenation attribute specifically for GET requests
    location: 'beijing'.key: 'abcd'
  }
// After concatenation, equivalent to http://xxx.com/page?location=beijing&key=abcd
}
Copy the code

Multi-request concurrency

  • Promise.all()
  • axios.all()
axios.all([axios(), axios()]).then(res= > {console.log(res); })// Returns two array representations of the request result

// If you don't want to display the result as an array, you can use spread() to display the result separately
axios.all([axios(), axios()]).then(axios.spread((res1, res2) = > {
  console.log(res1);
  console.log(res2);
}))
Copy the code

Global configuration

In real development, when many parameters are fixed and repeated, you can use defaults to set the global request configuration to extract them

// The data that needs to be written repeatedly for each request is placed here (public data)
axios.defaults.baseURL = 'http://xxx.com',
axios.defaults.timeout = 5000;     // The timeout period

axios({
  url: '/page'.// Extract the url without adding the domain name
}
Copy the code

Axios common configuration items

  • Url: Requested address (required)

  • Method: Request method. Default: GET

  • BaseURL: request root domain name (common)

  • TransformRequest: Allows some changes to the requested data before the request is sent to the server. These changes only apply to PUT, POST, and patch

  • TransformResponse: Allows data to be changed before it is sent to the THEN /catch method

  • Headers: Sets the JSON type of the request header and defines the request header information

  • Params: Parameter concatenation properties specifically for GET requests

  • Data: Data that needs to be sent as a request body. It applies only to PUT, POST, or patch. Data can be in FormData, File, or Blob format on the browser

  • Timeout: indicates the timeout period

  • WithCredentials: Indicates whether the request is cross-domain and the default is default

  • OnUploadProgress: Upload progress event

  • OnDownloadProgress: Event of download progress

  • MaxContentLength: Indicates the maximum value of the corresponding content

  • Auth: authentication of identity information

  • ResponseType: Request data format

Axios instance

When a large project has a large amount of concurrent data and may not have a single server requesting the data, a distributed request is used to request data from different servers using reverse proxies. Axios.create () is used to create an AXIOS instance.

const axiosInstance1 = axios.create({
  baseURL: 'http://xxx.com'.timeout: 5000
})

axiosInstance1({
  url: '/page/aaadata'
}).then(res= > {
  console.log(res);
})

axiosInstance1({
  url: '/page/bbbdata'
}).then(res= > {
  console.log(res);
})


const axiosInstance2 = axios.create({
  baseURL: 'http://yyy.com'.timeout: 10000
})

axiosInstance2({
  url: '/home'
}).then(res= > {
  console.log(res);
})

// Create two instances and request that the server address not in use be used without interference
Copy the code

The above code is written in main.js, but this is not usually done in real development. It is not recommended to import axios from ‘axios’ in every Vue page, because it is too cumbersome and depends too much on the third-party framework. If the framework is not updated and maintained, a lot of import dependencies in the project need to be modified, and the source code needs to be modified too much.

The solution is to uniformly encapsulate all network requests into the /network/require.js file.

import axios from 'axios'		// Import only once

// Create multiple AXIos instances that can be imported multiple times
// export function axiosInstance1(){}
// export function axiosInstance2(){}

export function request(config, success, failure){
// 1. Create an axios instance
const instance = axios.create({
 baseURL: 'http://xxx.com'.timeout: 5000
})

// Send the actual network request, but the normal callback function is not handled here and needs to be passed, so success and failure parameters are required
	instance(config)
 .then(res= > {
   success(res)
})
 .catch(err= > {
   failure(err)
})
}
Copy the code

Use in main.js

import {request} from './network/request';

// Process the result here
request({
 url: '/page'
	}, res= > {
 console.log(res);
}, err= > {
 console.log(err);
})
Copy the code


However, the above approach is still too decentralized and needs to be further encapsulated

export function request(config) {
return new Promise((resolve, reject) = > {
  const instance = axios.create({
     baseURL: 'http://xxx.com'.timeout: 5000
   })

 	instance(config)
   	.then(res= > {
     	resolve(res)
 		})
   	.catch(err= > {
     	reject(err)
 		})
	})
}
Copy the code

In the AXIos source code, the Promise is already called, and all of this simplifies the code without the need for Promise encapsulation

export function request(config) {
  const instance = axios.create({
    baseURL: 'http://xxx.com'.timeout: 5000
  })
  return instance(config)
}
Copy the code

Use in main.js

import {request} from './network/request';

// Process the result here
request({
  url: '/page'
}).then(res= > {
  console.log(res);
}).catch(err= > {
  console.log(err);
})
Copy the code

Axios interceptor

Axios provides interceptors for each request we send or receive.

axios.interceptors // Global interception
instance.interceptors // Instance interception

// Request interception
instance.interceptors.request.use(config= > {
  console.log(config);
  return config			// The interceptor has an interrupt mechanism and must return the data result after use otherwise AXIOS will fail to respond
}), err= > {
  console.log(err);
})

// Response interception
instance.interceptors.response.use(res= > {
  console.log(res);
  return res.data		// Return the data attribute
}, err= > {
  console.log(err);
})
Copy the code

When is interception required? 1. If some data in config does not meet the requirements of the server, interception is checked and returned to prevent hacker attacks or error submission. 2. Each time a network request is sent, you want a request load icon 3 to appear in the interface. For some network requests, special information must be carried (e.g., login token, token authentication)

During the development of the development project, try not to put all axios requests in one place. That is, instead of developing for only one request.js file, we can add an intermediate layer to a page or a component to facilitate maintenance and management.

If you save data to data, it will not be destroyed

Created or Mounted?

If all requests are created, too many requests and too slow loading will result in a brief white screen, generally

The interface is not complex and it’s going to be inside created,

If the interface is more complex, it will be placed in mounted.