1. Installation
1. Install npm install Axios using npm --save
2. Install bower install Axios with bower --save
3. Introduce <script src="https://unpkg.com/axios/dist/axios.min.js"></script>directly using cdn
2. Examples
1. Send a GET request
//Send a request with a given ID
axios.get('/user?ID=12345')
.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 once
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 is triggered when both requests are completed, and the two parameters represent the returned results
}))
III. API of axios
(1) axios can send requests by config
1, axios(config)
//Send a `POST`request
axios({
method:"POST",
url:'/user/12345',
data:{
firstName:"Fred",
lastName:"Flintstone"
}
});
2, axios(url[,config])
//Send a `GET` request (default request mode)
axios('/user/12345');
(2) Alias for the mode of request, which provides a convenient alias for all supported modes of request
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 using the alias method, the parameters url,method,data do not need to be declared in the configuration
(3) Concurrent requests, which are auxiliary functions to help process concurrent requests
//iterable is an iterative parameter 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. Method of Instance
- Here's the Instance method, noting that the defined configuration merges with the configuration of the instance created using 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]])
4. Configuration of Requests (request config)
- The following are the configuration options for the request, only the url option is required, and if the method option is undefined, it will send the request GET by default
{
//`url` is the requested server address
url:'/user',
//`method` is how resources are requested
method:'get'//default
//If `url` is not an absolute address, `baseURL` will be added before `url`
//Setting `baseURL'is convenient when `url' is a relative address
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 only applies 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 to suit 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 to suit your needs
return data;
}],
//`headers` option is custom request header information that needs to be sent
headers: {'X-Requested-With':'XMLHttpRequest'},
//`params` option is the request parameter to be sent with the request - General link after URL
//His type must be either a pure object or a URLSearchParams object
params: {
ID:12345
},
//`paramsSerializer` is an optional function designed to serialize parameters (params)
//For example (https://www.npmjs.com/package/qs,http://api.jquery.com/jquery.param)
paramsSerializer: function(params){
return Qs.stringify(params,{arrayFormat:'brackets'})
},
//`data` option is data that needs to be sent as a requester
//This option only applies to methods: `put/post/patch`
//dada must be one of several types when the `transformRequest'option is not set
//string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams
//Browser only: FormData/File/Bold
//Only node:Stream
data {
firstName:"Fred"
},
//The `timeout` option defines the number of milliseconds of delay that a request is made
//If the request takes longer than the delay, the request is terminated
timeout:1000,
//The `withCredentails'option indicates whether it is a cross-domain request?
withCredentials:false,//default
//`adapter`adapter option allows custom processing of requests, which makes testing easy
//Returns a promise and provides a validation return
adapter: function(config){
/*..........*/
},
//`auth` Indicates that HTTP-based authentication should be used and provides a certificate
//This sets an authorization header and overrides 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`Upload Progress Event
onUploadProgress:function(progressEvent){
//Download Progress Events
onDownloadProgress:function(progressEvent){
}
},
//Maximum value of corresponding content
maxContentLength:2000,
//`validateStatus` defines whether resolve or reject promise is based on the http corresponding status code
//If `validateStatus` returns true (or is set to `null` or `undefined`), then the state of promise will be resolved, otherwise it will be rejected
validateStatus:function(status){
return status >= 200 && status <300;//default
},
//`maxRedirects` defines the maximum number of redirections in nodejs
maxRedirects: 5,//default
//`httpAgent/httpsAgent`Defines a custom proxy to use when sending http/https requests
//keeyAlive is not activated by default in the selection
httpAgent: new http.Agent({keeyAlive:true}),
httpsAgent: new https.Agent({keeyAlive:true}),
//The proxy defines the host name and port number.
//`auth` indicates that http basic authentication should link to proxy proxy and provide a certificate
//This will set a `Proxy-Authorization`header and will overwrite the existing `Proxy-Authorization`header
proxy: {
host:'127.0.0.1',
port: 9000,
auth: {
username:'skda',
password:'radsd'
}
},
//`cancelToken` defines a cancel token to cancel a request
//See cancelation section for details
cancelToken: new cancelToken(function(cancel){
})
}
5. Contents Requested for Return
{
data:{},
status:200,
//http status text returned from the server
statusText:'OK',
//Response Header Information
headers: {},
//`config` is some configuration information when requested
config: {}
}
- You can do this to get response information
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); })
6. Default Configuration
- You can set the default configuration to be 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 default configuration when creating instances
var instance = axios.create({
baseURL: 'https://api.example.com'
});
//Modify configuration when instance is created
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
3. Priority in configuration
- The config configurations will be merged in priority, in the order of the default configurations in lib/defauts.js, then the default configurations in the instance, and finally the config parameters in the request. The higher the level backward, the later overrides the previous example.
//The default configuration in the libray directory is used when creating an instance
//Here the timeout configuration has a value of 0, which comes from the default value of libray
var instance = axios.create();
//Back override library defaults
//Now all requests will wait 2.5S before they are sent out
instance.defaults.timeout = 2500;
//Here timeout goes back to overwriting the previous 2.5S to 5s
instance.get('/longRequest',{
timeout: 5000
});
7. Interceptors
- 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 sent
return config;
},function(err){
//Do something with request error
return Promise.reject(error);
});
//Add a response interceptor
axios.interceptors.response.use(function(res){
//Processing the returned data here
return res;
},function(err){
//Do something with response error
return Promise.reject(error);
})
2. Cancel 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(){})
8. Error Handling
axios.get('/user/12345')
.catch(function(error){
if(error.response){
//The request has been sent, but is the status returned by the server response not within 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 the request is set
console.log('Error',error.message);
}
console.log(error.config);
});
9. Cancellation
-
You can cancel a request with a cancel token
-
You can create a cancel using 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 request (information parameters can be set)
source.cance("operation canceled 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();