[Collection of Dry Goods] axios Configuration Complete Book

  axios, javascript

I. installation

1. install npm installaxios using NPM-save
2. install bowerinstallaxios-save with bower.
3. directly use cdn to introduce < script src= “https://unpkg.com/axios/dist/ …; ></script>


II. Examples

1. Send a GET request

axios.get('/user?  ID=12345')// Send the request with the given ID
 .then(function(response){
 console.log(response);
 })
 .catch(function(err){
 console.log(err);
 });
 //The above request can also be sent in this way.
 axios.get('/user',{
 params:{
 ID:12345
 }
 })
 .then(function(response){
 console.log(response);
 })
 .catch(function(err){
 console.log(err);
 });

2. Send a POST request

axios.post('/user',{
 firstName:'Fred',
 lastName:'Flintstone'
 })
 .then(function(res){
 console.log(res);
 })
 .catch(function(err){
 console.log(err);
 });

3. Concurrent Multiple Requests at One Time

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){
 //This function will be triggered when both requests are completed. The two parameters respectively represent the returned results
 }))

Iii. apis for axios

Axios can send requests through configuration (config)

1、 axios(config)

//Send a POST' request
 axios({
 method:"POST",
 url:'/user/12345',
 data:{
 firstName:"Fred",
 lastName:"Flintstone"
 }
 });
 2、 axios(url[,config])

Send oneGETRequest (default request method) axios(‘/user/12345’);

(2) alias of request method, which provides convenient alias for all supported request methods

axios.request(config);
 
 axios.get(url[,config]);
 
 axios.delete(url[,config]);
 
 axios.head(url[,config]);
 
 axios.post(url[,data[,config]]);
 
 axios.put(url[,data[,config]])
 
 axios.patch(url[,data[,config]])

Note: When we use alias methods, the URL, method, and data parameters do not need to be declared in the configuration.

(3) concurrency is an auxiliary function to help handle concurrent requests

//iterable is a parameter that can be iterated, such as an array.
 axios.all(iterable)
 //callback will not execute until all requests are completed.
 axios.spread(callback)

(4) Create an axios instance and customize its configuration

1、 axios.create([config])
 
 var instance = axios.create({
 baseURL:"https://some-domain.com/api/",
 timeout:1000,
 headers: {'X-Custom-Header':'foobar'}
 });

2. Methods of Examples

The following is the instance method. Note that the already defined configuration will be merged with the configuration of the instance created by create

axios#request(config)
 
 axios#get(url[,config])
 
 axios#delete(url[,config])
 
 axios#head(url[,config])
 
 axios#post(url[,data[,config]])
 
 axios#put(url[,data[,config]])
 
 axios#patch(url[,data[,config]])

Iv. requested configuration (request config)

The following are the configuration options for the request. Only the url option is required. If the method option is not defined, then it will issue the request by GET by default

{
 //`URL`is the requested server address
 url:'/user',
 ///`method is the way to request resources
 method:'get'//default
 //If the url is not an absolute address, the baseurl will be added before the URL
 //When the url is a relative address, setting the baseURL is very convenient.
 baseURL:'https://some-domain.com/api/',
 The///`transformRequest option allows us to make some changes to the requested data before the request is sent to the server
 //this option is only applicable to the following request methods: `put/post/patch'
 //The last function in the array must return a string,-an' ArrayBuffer' or' Stream'
 transformRequest:[function(data){
 //Change the data here according to your needs.
 return data;
 }],
 The //`transformResponse' option allows us to make changes to the data before it is transferred to the then/catch' method
 transformResponse:[function(data){
 //Change the data here according to your needs.
 return data;
 }],
 The //`headers' option is the custom request header information that needs to be sent
 headers: {'X-Requested-With':'XMLHttpRequest'},
 The //`params' option is a request parameter to be sent with the request-usually linked after the URL
 //His type must be a pure object or URLSearchParams object
 params: {
 ID:12345
 },
 ///paramsSerializer an optional function that serializes parameters
 //for example (https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param)
 paramsSerializer: function(params){
 return Qs.stringify(params,{arrayFormat:'brackets'})
 },
 The //`data' option is data that needs to be sent as a request body.
 //This option only applies to methods: `put/post/patch'
 //dada must be one of the following types when the' transformRequest' option is not set
 //string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams
 //browser only: FormData/File/Bold
 //node only: stream
 data {
 firstName:"Fred"
 },
 The //`timeout' option defines the number of milliseconds that the request is delayed.
 //If the request takes longer than the delay, the request will be terminated
 
 timeout:1000,
 The///`withCredentails' option indicates whether it is a cross-domain request.
 
 withCredentials:false,//default
 The//`adapter`adapter option allows custom processing of requests, which makes testing convenient
 //return a promise and provide a verification return
 adapter: function(config){
 /*..........*/
 },
 ///`auth indicates that HTTP-based authentication should be used and provides a certificate
 //This will set an Authorization header and overwrite the authorization header information you set in the header.
 auth: {
 username:"zhangsan",
 password: "s00sdkf"
 },
 //Format of returned data
 //The options are ArrayBuffer, Blob, Document, JSON, Text, Stream
 responseType:'json',//default
 //
 xsrfCookieName: 'XSRF-TOKEN',//default
 xsrfHeaderName:'X-XSRF-TOKEN',//default
 ///`onUploadProgress Progress Events
 onUploadProgress:function(progressEvent){
 //Download Progress Events
 onDownloadProgress:function(progressEvent){
 }
 },
 //Maximum value of corresponding content
 maxContentLength:2000,
 ///`validateStatus defines whether to resolve or reject promise according to http's corresponding status code.
 //if validateStatus' returns true (or is set to null' or undefined'), then promise's status will be resolved, otherwise its status will be rejected
 validateStatus:function(status){
 return status >= 200 && status <300;  //default
 },
 //`maxredirects`defines the maximum number of redirects in nodejs
 maxRedirects: 5,//default
 //`http agent/httpagent`defines a custom agent to use when sending http/https requests
 ///keeyAlive is not activated by default in the option
 httpAgent: new http.Agent({keeyAlive:true}),
 httpsAgent: new https.Agent({keeyAlive:true}),
 //proxy defines the host name and port number.
 ///`auth indicates that http basic authentication should be linked with proxy agent and provide certificate
 //This will set a' proxy-authorization' header and overwrite the existing' proxy-authorization' header
 proxy: {
 host:'127.0.0.1',
 port: 9000,
 auth: {
 username:'skda',
 password:'radsd'
 }
 },
 //`cancel token`defines a CancelToken to cancel the request
 //See cancelation for details.
 cancelToken: new cancelToken(function(cancel){
 
 })
 }

Five, the content of the request to return

{
 
 data:{},
 status:200,
 //http status text returned from server
 statusText:'OK',
 //response header information
 headers: {},
 ///`config is some configuration information at the time of request
 config: {}
 }

You can get the response information in this way.

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

VI. Default Configuration

You can set the default configuration, which is valid for all requests.

1. Global Default Configuration

axios.defaults.baseURL = 'http://api.exmple.com';
 axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
 axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';

2. Custom Instance Default Settings

//Configure the default configuration when creating an instance

var instance = axios.create({
 baseURL: 'https://api.example.com'
 });

//Modify the configuration when the instance is created
instance.defaults.headers.common[“Authorization”] = AUTH_TOKEN;
3. Priority in configuration

Config configuration will be merged with priority level, the order is the default configuration in lib/defauts.js, then the default configuration in the instance, and finally the configuration of config parameter in the request. the higher the later level, the later will overwrite the previous example.
 //The default configuration in the libray directory will be used when creating an instance.
 //The timeout configuration value here is 0, which comes from the default value of libray.
 var instance = axios.create();
 //Overwrite the default value of library
 //Now all requests will not be sent until 2.5S
 instance.defaults.timeout = 2500;
 //The timeout here changes from 2.5S before overwriting to 5s
 instance.get('/longRequest',{
 timeout: 5000
 });

VII. Interceptor

You can intercept requests and responses before they reach then/catch.
 
 //Add a Request Interceptor
 axios.interceptors.request.use(function(config){
 //Do something before the request is issued
 return config;
 },function(err){
 //Do something with request error
 return Promise.reject(error);
 });
 //Add a response interceptor
 axios.interceptors.response.use(function(res){
 //process the returned data here
 return res;
 },function(err){
 //Do something with response error
 return Promise.reject(error);
 })

2, cancel the interceptor

var myInterceptor = axios.interceptor.request.use(function(){/…./});
axios.interceptors.request.eject(myInterceptor);

3. Add interceptors to custom axios instances

var instance = axios.create();
 instance.interceptors.request.use(function(){})

Eight, error handling

axios.get('/user/12345')
 .catch(function(error){
 if(error.response){
 //The request has been issued, but the status returned by the server response is not in the range of 2xx
 console.log(error.response.data);
 console.log(error.response.status);
 console.log(error.response.header);
 }else {
 //Some errors are triggered when setting the request
 console.log('Error',error.message);
 }
 console.log(error.config);
 });

IX. Cancellation

You can cancel a request through a cancel token. You can create a Cancel through the CancelToken.source factory function
token

var CancelToken = axios.CancelToken;
 var source = CancelToken.source();
 
 axios.get('/user/12345',{
 cancelToken: source.token
 }).catch(function(thrown){
 if(axios.isCancel(thrown)){
 console.log('Request canceled',thrown.message);
 }else {
 //handle error
 }
 });

//cancel the request (parameters of information can be set)
Source.cance (“operation cancelled by user”);

You can pass an executor function to the cancelToken constructor to create a cancel token:

var cancelToken = axios.CancelToken;
 var cance;
 axios.get('/user/12345',{
 cancelToken: new CancelToken(function(c){
 //This executor function accepts a cancel function as an argument
 cancel = c;
 })
 })

//cancel request
cancel();