web123456

axios basics

Article Catalog

  • preamble
  • I. The return of data sent by axios
    • 1, by default, the http status code is 2 to start, then let the promise state successful
    • 2, customize the HTTP status code returned by the service for how much is success, for how much failure!
  • Second, the way to send a request based on axios
    • 1. axios([config]) or axios([url],[config])
    • 2、([config])
    • 3、/delete/head/options([url],[config])
    • 4. Create an axios instance to initiate the request
  • Third, axios sends the request when the configuration item config
    • 1、url
    • 2、Generic prefix for baseURL request address
    • 3、transformRequest
    • 4、transformResponse
    • 5. headers:{...} Customizing request headers
    • 6、 params:{...}
    • 7、data:{...}
    • 8、 timeout:0 set the timeout time, write 0 is not to set the
    • 9、 withCredentials:false Whether or not to allow carrying resource credentials in CORS cross-domain requests
    • 10, responseType: the server to return the results set to the specified format
    • 11、 onUploadProgress:progressEvent=>{}
    • 12、 validateStatus
  • IV. Cancellation
  • V. Interceptors
    • 5-1. request interceptor:
    • 5-1. Response Interceptor


preamble

Hint: axios is based on a promise wrapper library [the core is still based on XMLHttpRequest to send requests].


Tip: /zh-cn/docs/

One,axiosReturn of sent data

Sending data requests based on axios returns results that are apromisean actual example

1. By default, httpstatus codeis 2 to start, then let the promise state succeed

  • The http status code returned by the server starts at 2, then let the promise state succeed, the value is a resolve object
 response = {
          config:{...}, Configuration items for sending axios requests
          data:{...}, The body of the response from the server
          headers:{...}, The response header information returned by the server
          request:XMLHttpRequest instance object, Native xhr objects
          status:200, server-responsiveHTTPStatus Code
          statusText:'OK' Description of the status code
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • Promise status is failure
    1, the server has returned information [response object does not exist], only the http status code does not start with 2
reason = {
            config:{...},
            isAxiosError: true,
            request:XMLHttpRequest instance object,
            response:Equivalent to a successfully fetched response object,
            toJSON:function...,
            message:'xxx',
            ...
        };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述
2. The request timed out or the request was interrupted.
在这里插入图片描述
3, disconnected, characteristics: no feedback from the server

2, customize the HTTP status code returned by the service for how much is success, for how much failure!

Official Site Description:
validateStatus Defines whether the response status code for a given HTTP response is resolve or reject promise. IfvalidateStatus come (or go) backtrue (or set tonull maybeundefined),promise will be resolve; if not,promise will be rejecte

 // axios' validateStatus configuration item, which is the condition that the status of the customized promise instance is successful
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  • 1
  • 2
  • 3
  • 4
  • 5

Second, the way to send a request based on axios

1. axios([config]) or axios([url],[config])

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

// Get the remote image
axios({
	method:'get',
		url:'/user/list',
		params:{
			departmentId:0
		}
	})
.then((response)=>{
	console.log('res',response)
})
.catch((error)=>{
	console.log('error',error)
})



 try{
     let  response = await axios('/user/list',{
      params:{
        departmentId:0
      },
      validateStatus: (status) => {
        return status >= 200 && status < 300; // Default processing mechanism
      }
    })
 console.log('res',response)
  }catch(response){
    console.dir(response)

  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

2、axios.request([config])

try{
       let  response = await axios.request({
		   	url:'/user/list',
			params:{
				departmentId:0
			},
			validateStatus: (status) => {
				return status >= 200 && status < 300; // Default processing mechanism
			}
      })
	  console.log('res',response)
    }catch(response){
      console.dir(response)

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

3、/delete/head/options([url],[config])

(url[, config])
(url[, config])
(url[, config])
(url[, config])
(url[, data[, config]])
(url[, data[, config]])
(url[, data[, config]])
take note of
The url, method, and data attributes do not need to be specified in the configuration when using alias methods. # Summary

4. Create an axios instance to initiate the request

let instance = ([config])
The created instance is equivalent to axios and is used just like axios...
([url],[config])

Instance Methods
The following methods are available for instances. The specified configuration will be 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]])

Third, axios sends the request when the configuration item config

1、url

url: the address of the request When sending a request, you need to specify the url in the configuration item if you don't have a separate url.

2、Generic prefix for baseURL request address

When the request is finally sent, it is sent by splicing the baseURL and the url together
(’/user/list’,{
baseURL:‘’,

});
The last address to send a request to is '/user/list'
Special case: if the url address itself already has http or https information, it means that the url itself is already a complete address, and the baseURL value does not need to be spliced.

3、transformRequest

transformRequest Allow request data to be modified before sending it to the server.
Can only be used in 'PUT', 'POST' and 'PATCH' request methods.
Functions in the latter array must return a String, or ArrayBuffer, or Stream
Make changes to the results returned by the server before our own .then/catch

  transformRequest: [function (data, headers) {
    // Perform arbitrary transformations on the data
    return data;
  }],
  • 1
  • 2
  • 3
  • 4

It's "for POST series requests only", formatting our own pass [data] into the specified format, and sending it to the server based on the body of the request at a later stage!!!!
axios does a process internally to automatically set the Content-Type value in the request header based on the format of the last [data] we processed!!!! "may not be completely accurate"
@1 Data format passed by the client to the server based on the body of the request
+ form-data Content-Type:multipart/form-data Mainly used for file upload/form submission.
+ urlencoded Content-Type:application/x-www-form-urlencoded
GET series of requests: is based on the URL question mark to pass parameters to thepass on informationTo the server ?xxx=xxx&xxx=xxx
xxx=xxx&xxx=xxx This string is a urlencoded string.
+ raw Generic, referring to text formatting "including: normal formatted text strings, JSON formatted strings, ...".
Ordinary string Content-Type:text/plain
JSON format string Content-Type:application/json

+ binary format data Mainly used for file uploads.
By default, @2 axios will pass the object as a JSON string to the server if we pass a normal object in [data] and it's not processed by transformRequest.

await axios.post(
		 '/user/login',
		{
			account:"18379005583",
			password:"123456"
		},
		{
		transformRequest:(data)=>{
			return qs.stringify(data)
		}
		}
	 )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Such a request ends up being passed in the following form. qs does the work of converting the data to a urlencoded string
在这里插入图片描述
return (data)change intoreturn data then it is also an object
在这里插入图片描述
If the data passed is in a formdata format, then no qs processing is needed, only if it is a pure object.
Modify the above request as follows:

let fm = new FormData()
	 fm.append("account","3787")
	 await axios.post(
		 '/user/login',
		// fm,
		// {
		// 	username:'uuuu',
		// 	password:'899'
		// },
		'****',
		{
		transformRequest:(data)=>{
				return isPlainObject(data) ? qs.stringify(data) :data
			}
		}
	 )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Pass in fm, plain objects, and strings, respectively. The browser's request parameters look like this
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
So be judicious.isPlainObject(data) ? (data) :data. Is it a pure object
Code to determine if it is a pure object

// Detect if it is a pure object
export const isPlainObject = function isPlainObject(obj) {
    let proto, Ctor;
    if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false;
    proto = Object.getPrototypeOf(obj);
    if (!proto) return true;
    Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
    return typeof Ctor === "function" && Ctor === Object;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4、transformResponse

Make changes to the results returned by the server before our own .then/catch

transformResponse:data=>{
        // data: the result from the server, and is the response body information "The information returned by the server response body is usually a JSON format string".
        return data;
     };
  • 1
  • 2
  • 3
  • 4
'
(of a computer) run

5、 headers:{...} Customize request header information

6、 params:{…}

The GET series of requests, based on the URL question mark parameter, passes information to the server; our params are usually set to objects, which axios internally turns into urlencoded format spliced into the end of the URL

7、data:{…}

The POST series of requests, based on information passed by the requesting body...

8、 timeout:0 set the timeout time, write 0 is not to set the

9、 withCredentials:false Whether or not to allow carrying resource credentials in CORS cross-domain requests

10, responseType: the server to return the results set to the specified format

'arraybuffer', 'blob', 'document', 'json 'default', 'text', 'stream' ...

11、 onUploadProgress:progressEvent=>{}

 onDownloadProgress:progressEvent=>{}
 Listen to the progress of uploads and downloads
  • 1
  • 2

12、 validateStatus

status=>status>=200 && status<300
Define what the status of the server return is that the promise instance was successful

IV. Cancellation

The cancelation of an axios request depends on the completion of the
const source = ();
([url],{
…,
cancelToken: ,
}).catch(reason=>{
// After canceling, the promise instance fails.
});
('...'); unsend

	const source = axios.CancelToken.source()
     let fm = new FormData()
	 fm.append("account","3787")
	 axios.post(
		 '/user/login',
		// fm,
		{
			username:'uuuu',
			password:'899'
		},
		// '****',
		{
			transformRequest:(data)=>{
				return isPlainObject(data) ? qs.stringify(data) :data
			},
			transformResponse:(data)=>{
				console.log(data)
				return JSON.parse(data)
			},
			cancelToken:source.token
		}
	 )
	 .then((res)=>{
		 console.log(res)
	 })
	 .catch((error)=>{
		 console.log(error)
	 })
	setTimeout(()=>{
		source.cancel('cancel')
	})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

V. Interceptors

5-1. request interceptor:

When axios has taken care of all aspects of the configuration and is about to send a request to the server based on these configuration items, the request interceptor is triggered

 axios.interceptors.request.use(config=>{
     // config stores the configuration that axios handles well, and we generally change it in the request interceptor
     //...
     return config;
  });
  • 1
  • 2
  • 3
  • 4
  • 5

5-1. Response Interceptor

The server returns the result, and axios already knows whether the state of the returned promise instance is success or failure, and executes the method set in the response interceptor based on the promise state before calling .then/catch itself!

 axios.interceptors.response.use(
      response=>{
          The //promise instance is successful, execute this method: response stores the result returned by the server
      },
      reason=>{
          //promise instance is failing, execute this method: reason stores the reason for failure
      }
  );
  axios.get([url],[config])
    .then(value=>{})
    .catch(reason=>{});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Official Documentation:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // What to do before sending a request
    return config;
  }, function (error) {
    // Do something about the request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with the response data
    return response;
  }, function (error) {
    // Do something about response errors
    return Promise.reject(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17