A, install,

NPM install axios –save

Bower install axios –save

3, direct use of CDN is introduced into < script SRC = “https://unpkg.com/axios/dist/axios.min.js” > < / script >

Second, the example

1. Send a GET request

// Send the request with the given ID
axios.get('/user? ID=12345')
  .then(function(response){
    console.log(response);
  })
  .catch(function(err){
    console.log(err);
  });
// The above requests 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);
});
Copy the code

2. Send a POST request

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

3. Multiple requests at a 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 is triggered when both requests are completed, with two arguments representing the result returned
  }))
Copy the code

The AXIos API

(A) Axios can be configured (config) to send the request

1, axios (config)

// Send a POST request
axios({
    method:"POST",
    url:'/user/12345'.data:{
        firstName:"Fred",
        lastName:"Flintstone"}});Copy the code

2, axios ([url, config])

// Send a 'GET' request (default request)
axios('/user/12345');
Copy the code

(2) Aliases for request methods. Convenient aliases are provided 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]])
Copy the code
  • Note: When we use the alias method,url,method,dataThese parameters do not need to be specified in the configuration

Concurrency. Concurrency is an auxiliary function that helps you handle concurrent requests

// Iterable is an iterable set of parameters
axios.all(iterable)
// Callback will not be executed until all requests are completed
axios.spread(callback)
Copy the code

(4) create aaxiosInstance, and you 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'}});Copy the code

2. Method of instance

  • Here is the instance method, noting that the configuration defined will be merged 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]])
Copy the code

4. Request Config

  • Here are the configuration options requested, onlyurlThe option is required ifmethodOption is not defined, then it defaults toGETTo make a request
{
  // 'url' is the requested server address
  url:'/user'.// 'method' is the method of requesting the resource
  method:'get'//default
  // If 'url' is not an absolute address, 'baseURL' will be appended to 'url'
  // When 'url' is a relative address, setting 'baseURL' is very convenient
  baseURL:'https://some-domain.com/api/'.// The 'transformRequest' option allows us to make some changes to the requested data before it is sent to the server
  // This option only applies to 'PUT/POST /patch' requests
  // The last function in the array must return a string, - an ArrayBuffer, or a Stream
  transformRequest: [function(data){
    // Change the data here to suit your needs
    returndata; }].// The 'transformResponse' option allows us to make changes to the data before it is sent to the 'then/catch' method
  transformResponse: [function(data){
    // Change the data here to suit your needs
    returndata; }].// The 'headers' option is a custom request header to be sent
  headers: {'X-Requested-With':'XMLHttpRequest'},
  // The 'params' option is the request parameter to be sent with the request ---- is usually linked after the URL
  // Its type must be a pure object or URLSearchParams object
  params: {
    ID:12345
  },
  // 'paramsSerializer' is an optional function that serializes parameters (params)
  / / (https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param, for example)
  paramsSerializer: function(params){
    return Qs.stringify(params,{arrayFormat:'brackets'})},// The 'data' option is the data to be sent as a request body
  // This option applies only 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
  // Only browser: FormData/File/Bold
  / / the node only: the Stream
  data {
    firstName:"Fred"
  },
  // The 'timeout' option defines the number of milliseconds the request will be delayed
  // If the request takes longer than the delay, the request is aborted

  timeout:1000.// The 'withCredentails' option indicates whether the request is cross-domain
  
  withCredentials:false.//default
  The adapter option allows you to customize processing requests, which makes testing easier
  // Return a promise and provide a validation return
  adapter: function(config){
    / *... * /
  },
  // 'auth' indicates that HTTP-based authentication should be used and certificates provided
  // This sets an authorization header and overwrites the authorization header you set in the header
  auth: {
    username:"zhangsan".password: "s00sdkf"
  },
  // The format of the returned data
  / / its option is 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){}},// The maximum value of the corresponding content
  maxContentLength:2000.// 'validateStatus' defines whether to resolve or reject a promise according to the corresponding HTTP status code
  // If 'validateStatus' returns true(or set to' null 'or' undefined '), then the promise state will be Resolved, otherwise it will be rejected
  validateStatus:function(status){
    return status >= 200 && status <300;//default
  },
  // 'maxRedirects' defines the maximum number of redirects in nodejs
  maxRedirects: 5.//default
  // 'httpAgent/httpsAgent' defines the custom proxy 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 to a proxy and provide a certificate
  // This will set a proxy-authorization header and override the existing proxy-authorization header
  proxy: {
    host:'127.0.0.1'.port: 9000.auth: {
      username:'skda'.password:'radsd'}},// 'cancelToken' defines a cancel token used to cancel a request
  // See Cancelation
  cancelToken: new cancelToken(function(cancel){})}Copy the code

Fifth, the content of the request returned

{
  data:{},
  status:200.// HTTP status text returned from the server
  statusText:'OK'.// Response header information
  headers: {},
  // 'config' is some configuration information at the time of request
  config: {}
}
Copy the code
  • You can get response information like this
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);
  })
Copy the code

Default configuration

  • You can set the default configuration to work 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';
Copy the code

2. Custom instance default Settings

// Configure the default configuration when creating the 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;
Copy the code

3. The configuration has a priority

  • The config configuration will be combined in priority order, 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, as the hierarchy increases, and the latter overrides the previous example.
// The default configuration in the Libray directory is used when creating an instance
// In this case the value of timeout is 0, which comes from the default value of Libray
var instance = axios.create();
// Override the library defaults
// Now all requests are sent after 2.5s
instance.defaults.timeout = 2500;
// The timeout restores the previous 2.5s to 5s
instance.get('/longRequest',{
  timeout: 5000
});
Copy the code

7. Interceptor

  • You can request and respond on arrivalthen/catchIntercept them before
// 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){
  // This is where the returned data is processed
  return res;
},function(err){
  //Do something with response error
  return Promise.reject(error);
})
Copy the code

2. Cancel the interceptor

var myInterceptor = axios.interceptor.request.use(function(){/ *... * /});
axios.interceptors.request.eject(myInterceptor);
Copy the code

3. Add interceptors to custom AXIos instances

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

4. Sequence of interceptor execution

axios.interceptors.request.use(function(config) {
    / / send the token
    console.log('axios.interceptors.request - 1');
    return config;
}, function() {}); axios.interceptors.request.use(function(config) {
    console.log('axios.interceptors.request - 2');
    return config;
}, function() {});// axios => function request() => .get .post .delete

axios.interceptors.response.use(function(data) {
    console.log('axios.interceptors.response - 1');
    console.log('data', data);
    return data;
}, function() {}); axios.interceptors.response.use(function(data) {
    console.log('axios.interceptors.response - 2');
    console.log('data', data);
    return data;
}, function() {});/ / execution sequence: axios. Interceptors. Request - 2
// axios.interceptors.request-1
// axios.interceptors.response-1
// axios.interceptors.response-2
Copy the code

this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
	chain.unshift(interceptor.fulfilled, interceptor.rejected);
});

this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
	chain.push(interceptor.fulfilled, interceptor.rejected);
});
Req2-req1-resp2; req2-req1-resp2; req2-req1-resp2
Copy the code

Error handling

axios.get('/user/12345')
  .catch(function(error){
    if(error.response){
      // The request has been sent, but the status returned by the server response is outside 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);
  });
Copy the code

Nine, cancellation,

  • You can go through onecancel tokenTo cancel a request
  1. You can go throughCancelToken.sourceFactory function to create onecancel 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 (information parameters can be set)
source.cancel("Operation cancelled by user");
Copy the code
  1. CancelToken You can create a cancel token by passing an executor function to the cancelToken constructor:
var cancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {cancelToken: new CancelToken(function(c){
    // This executor function takes a cancel function as an argumentcancel = c; })})// Cancel the request
cancel();
Copy the code