First, installation
1. Installing with NPMnpm install axios --save
2. Installation with Bowerbower install axios --save
3, direct use of CDN introduced<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Ii. examples
1. Send a GET
request
//通过给定的ID来发送请求axios.get(‘/user?ID=12345‘) .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); });//以上请求也可以通过这种方式来发送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, one-time concurrent multiple requests
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){ //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果 }))
Third, Axios API (a) Axios can be configured (
config
) to send the request
1.axios(config)
//发送一个`POST`请求axios({ method:"POST", url:‘/user/12345‘, data:{ firstName:"Fred", lastName:"Flintstone" }});
2.axios(url[,config])
//发送一个`GET`请求(默认的请求方式)axios(‘/user/12345‘);
(b), the alias of the request, which provides a convenient alias for all the 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 the alias method,
url,method,data
These parameters do not need to be declared in the configuration
(iii), concurrent requests (concurrency), which are auxiliary functions that help handle concurrent requests
//iterable是一个可以迭代的参数如数组等axios.all(iterable)//callback要等到所有请求都完成才会执行axios.spread(callback)
(iv), create a
axios
instance, and can 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. Examples of methods
- Is the instance method, note that the configuration that has already been defined will be merged with the configuration of the instance created with 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. Configuration of requests (Request config)
- Here is the configuration option for the request, only the
url
option is required, and if the option is undefined method
, it is GET
the default way to make the request
{//' URL ' is the requested server address URL: '/user ',//' method ' is the way to request the resource method: ' Get '//default//If ' URL ' is not an absolute address, then ' BaseURL ' will be added to the ' URL ' in front//when ' URL ' is relative address, setting ' BaseURL ' will be very convenient BaseURL: ' https://some-domain.com/api/',//' 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: ' Put/post/patch '//The last function inside the array must return a string, a ' ArrayBuffer ' or ' Stream ' Transformrequest:[function (data) {//In this case to change the information according to their own needs; }],//' transformresponse ' option allows us to make changes to the data before the data is transferred to the ' Then/catch ' method transformresponse:[function (data) {//where it is changed according to its own requirements R Eturn data; }],//' headers ' option is a custom request header message 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 the URL//his type must be a plain object or a Urlsearchparams object params: {id:12345},//' Paramsserializer ' is an optional letter Number, the function is to let the parameter (params) serialize//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 required to be sent as a request body//This option applies only to methods: ' put/post/pAtch '//When the ' transformrequest ' option is not set Dada must be one of several types//string/plain/object/arraybuffer/arraybufferview/ Urlsearchparams//Browser only: Formdata/file/bold//Only node:stream data {firstName: "Fred"},//' timeout ' option defines the number of delay milliseconds the request is issued /If the request takes longer than the delay time, then the request is terminated timeout:1000,//' withcredentails ' option indicates whether it is a cross-domain request Withcredentials:false,//default//' The adapter ' adapter option allows custom processing requests, which makes testing easy//Returns a promise and provides validation return Adapter:function (config) {/*..........*/},//' auth ' indicating http The underlying authentication should be used and provided with a certificate//This will set a authorization header (header) and overwrite the authorization header information you set in the header auth: {username: "Zhangsan", Passwo RD: "S00SDKF"},//format of the returned data//its optional is Arraybuffer,blob,document,json,text,stream responsetype: ' json ',//default//Xsrfco Okiename: ' Xsrf-token ',//default xsrfheadername: ' X-xsrf-token ',//default//' onuploadprogress ' upload Progress Event Onuploadprogress:function (progressevent) {//Download Progress event ondownloadprogress:function (progressevent) {}},//maximum value of the corresponding content maxcontentlength:2000,//' Validatestatus ' defines whether to resolve or reject p according to the corresponding status code of the HTTPRomise//If ' Validatestatus ' returns True (or set to ' null ' or ' undefined ') then the promise state will be resolved, otherwise its state is rejected Validatestatus:function (status) {return status >= && status <300;//default},//' maxredirects ' defines the n The maximum number of redirects in Odejs maxredirects:5,//default//' httpagent/httpsagent ' defines the custom proxy to be used when sending the HTTP/HTTPS request// Keeyalive is not activated by default in the Options 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 to the proxy agent 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: ' SK Da ', Password: ' RADSD '},//' Canceltoken ' defines a cancel token for cancellation of the request//See cancelation section canceltoken:new Cancelto Ken (function (cancel) {})}
V. Content requested for return
{ data:{}, status:200, //从服务器返回的http状态文本 statusText:‘OK‘, //响应头信息 headers: {}, //`config`是在请求的时候的一些配置信息 config: {}}
- You can do this to get the 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); })
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
//当创建实例的时候配置默认配置var instance = axios.create({ baseURL: ‘https://api.example.com‘});//当实例创建时候修改配置instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
3. Priority in Configuration
- The config configuration will be merged with the priority level, which is the default configuration in Lib/defauts.js, then the default configuration in the instance, and finally the configuration of the Config parameter in the request, the higher the back level, the later the previous example is overwritten.
//创建一个实例的时候会使用libray目录中的默认配置//在这里timeout配置的值为0,来自于libray的默认值var instance = axios.create();//回覆盖掉library的默认值//现在所有的请求都要等2.5S之后才会发出instance.defaults.timeout = 2500;//这里的timeout回覆盖之前的2.5S变成5sinstance.get(‘/longRequest‘,{ timeout: 5000});
Seven, interceptors
- You can intercept requests and responses
then/catch
before they arrive.
//添加一个请求拦截器axios.interceptors.request.use(function(config){ //在请求发出之前进行一些操作 return config;},function(err){ //Do something with request error return Promise.reject(error);});//添加一个响应拦截器axios.interceptors.response.use(function(res){ //在这里对返回的数据进行处理 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){ //请求已经发出,但是服务器响应返回的状态吗不在2xx的范围内 console.log(error.response.data); console.log(error.response.status); console.log(error.response.header); }else { //一些错误是在设置请求的时候触发 console.log(‘Error‘,error.message); } console.log(error.config); });
Ix. Cancellation of
- You can
cancel token
cancel a request by one.
- You can use the
CancelToken.source
factory function to create acancel 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 }});//取消请求(信息的参数可以设置的)source.cance("操作被用户取消");
- You can pass a 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){ //这个executor函数接受一个cancel function作为参数 cancel = c; })})//取消请求cancel();
Links: http://www.jianshu.com/p/df464b26ae58
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Axios Using Tutorials