Application of axios class library

What is axios

Axios Is an Ajax Library Based on promise encapsulation. The core is XMLHttpRequest, which can be used in browsers and node JS

characteristic:

  • Create XMLHttpRequests from the browser
  • From node JS create http request
  • Promise API supported
  • Intercept requests and responses
  • Convert request data and response data
  • Cancel request
  • Automatically convert JSON data
  • Client support defense XSRF

install

Using NPM: NPM install Axios
Using bower: bower install Axios
Using CDN: < script SRC=“ https://unpkg.com/axios/dist/axios.min.js "></script>

Method of axios object

  • axios(config) / axios(url[, config]): you can create a request by passing the relevant configuration to axios
  • Cancel / CancelToken: used to cancel an ajax request
  • all([iterable]): Based on promise All implements ajax parallelism. After all requests are successful, a successful promise instance is returned
  • spread([callback]): parse the results returned based on all
  • get/delete/head/options send request of corresponding method
  • post/put/patch sends the request of corresponding mode
  • Request send request
  • interceptors interceptor
    • request interceptor
    • response interceptor
  • ...

axios itself is a function. Based on the requests sent by axios, all returned are promise instances (axios. axios is called internally),

Parameters received by then:

  • response.data
  • response.status
  • response.statusText
  • response.headers
  • response.config

Request configuration

Configuration item : only url is required. If no method is specified, the request will use the get method by default.

axios({
	// baseURL+url: the address of the final request. baseURL will be automatically added in front of the URL, unless the URL is an absolute URL
	baseURL: 'https://some-domain.com/api/', 
	url: '/user', 
	
	//Is the method used when creating the request. The default is get 
  	method: 'get', 	
	
	//Request header information
	headers: {
		'X-Requested-With': 'XMLHttpRequest',
		common:{
			"x-Token":"xxx"
		},
		//Set only for one request
		post:{},
		get:{}
	},
  	
  	//Params: Based on "?", Splice the params object item by item to the end of the URL and pass it to the server
  	// Must be a plain object or URLSearchParams object
	params: { 
		ID: 12345,
		name:"kk"	
	},
	
	//Functions responsible for params serialization
	//https://www.npmjs.com/package/qs || http://api.jquery.com/jquery.param/
	paramsSerializer: function(params) {
		return Qs.stringify(params, {arrayFormat: 'brackets'})
	},

	//Data: only applicable to POST series requests. The data sent as the request subject,
	//By default, the object will be changed into application/json string and passed to the server. The value is: FormData/binary/raw
	data: { firstName: 'Fred'},
	
	//In the POST series of requests, it is allowed to arbitrarily convert the response data before passing it to then/catch
	transformResponse:function (data) {  return data },	
	
	//Under the POST request, it is allowed to arbitrarily convert the request subject information before sending it to the server
	transformRequest: [function (data, headers) {
	// Judge whether the data must be a pure object or try catch processing
	// isPlanObject(data),utils.js judge pure objects
	  return Qs.stringify(data);
	}],	
	//Scattered configuration
 	// Specifies the number of milliseconds that the request times out. If the call cost exceeds the timeout, the request will be interrupted
	timeout: 1000,
	//Indicates whether credentials are required for cross domain requests
	withCredentials:true, // default: false
 	//Allow user-defined processing of requests, return a promise and apply a valid response [similar to request interceptor]
  	adapter: function (config) { /* ... */ },
  	//Preset the data type of the server response: arraybuffer/blob/document/json/text/stream
  	//No matter what format the server returns, it is internally converted to the preset format
  	responseType: 'json', // default
	//Monitor upload / download progress
	onUploadProgress: function (progressEvent) {/* ... */ },
  	onDownloadProgress: function (progressEvent) {/*Handling of native progress events*/},
	
	 //The successful response status code of internally defined HTTP is promise of resolve/reject.
	 //Return true/null/undefined, promise will be resolve d; Otherwise, promise will be rejecte d
	validateStatus: function (status) {
    	return status >= 200 && status < 300; // default
	},
	
  	//Define the host name and port of the proxy server
	proxy: {
	  host: '127.0.0.1',
	  port: 9000,
	  auth: {//Indicates that HTTP basic authentication should be used for connection proxy and provide credentials
	    username: 'mikeymike',
	    password: 'rapunz3l'
	  }
	},
	//Used to cancel the request
	cancelToken: new CancelToken(function (cancel) {
	})
//...
})

Request method alias

For convenience, aliases are provided for all supported request methods

  • axios.request([config])
  • axios.[ get/ head/ delete/ options ] ( [url],[config])
  • axios.[ post/ put/ patch ] ([url], [data], [config])
//GET
axios.get("http://127.0.0.1:5500/20210526/index.html",{
    params:{
        name:"kk",
        age:18
    }
}).then(response => {	
	//-config: set configuration item
	//-headers: response header information
	//-request: native XHR object
	//-status/statusText status code and description of status code 
	//-data: response subject information
    console.log("success" ,response);
}).then(data => {	
	//Obtain the response subject information and complete the corresponding business logic
    console.log("success" ,data );
}).catch(reason => {	
    console.log("fail",reason);
})

then:

  • Success: the status code returned by the server is consistent with the validateStatus condition (readyState===4)
  • Available information:
    • config: set configuration item
    • headers: response header information
    • request: native XHR object
    • status/statusText status code and description of status code
    • data: response subject information

catch:

  • Failed:
    • The status code returned by the server is inconsistent with the validateStatus condition [at least the server returns]
    • There is no return from the server, such as disconnection / timeout exceeded / canceltoken
  • Available information:
    • config: set configuration item
    • request: native XHR object
    • toJSON: convert the obtained information into JSON objects
    • Message: error message
    • Response: if the network layer fails, there is no response. If only the Axios layer fails, there is a response
    • isAxiosError: whether it is an Axios layer failed

Success and failure of requests

  • Network layer failure: the request is not sent successfully, or there is no response [an HTTP transaction is not completed]
  • AXIOS tier failed:
    • The server must have returned
    • But the status code is inconsistent with validateStatus
    • Timeout or cancel request
  • Business layer failure: generally, the server distinguishes different business forms and results based on business requirements and symbols such as code

Keywords: ECMAScript

Added by Dlex on Tue, 08 Feb 2022 10:32:26 +0200