ajax component request API recommended by axios.js

Keywords: axios npm JQuery JSON

I. installation

1. Install NPM install Axios using npm--save
2. Install bower install Axios with bower--save
3. Introducing <script src="https://unpkg.com/axios/dist/axios.min.js"> </script> directly using cdn

Two, example

1. Send a GET request

//Send requests 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 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 is triggered when both requests are completed, and the two parameters represent the returned results, respectively.
  }))

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 mode of request)
axios('/user/12345');

(2) Aliases for requests, which provide convenient aliases for all supported requests

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 parameters do not need to be declared in the configuration.

(3) concurrency, which is an auxiliary function to help process concurrent requests

//iterable is a parameter that can be iterated, such as an array, etc.
axios.all(iterable)
//callback will not be executed until all requests have been 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 Examples

  • 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]])

request config

  • Here are the configuration options for requests. Only the url option is required. If the method option is undefined, it defaults to GET the request.
{
  //` url ` is the requested server address
  url:'/user',
  //` method `is the way to request resources
  method:'get'//default
  //If `url'is not an absolute address, then `base URL' will be added to the front of `url'.
  //When `url'is the relative address, it is very convenient to set `base URL'.
  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 applies only to the following request modes: `put/post/patch`
  //The last function in the array must return a string, - an `Array Buffer'or `Stream'.`
  transformRequest:[function(data){
    //Change the data here according to your needs
    return data;
  }],
  //` The transformResponse `option allows us to change 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 - - typically linked after the URL
  //His type must be a pure object or a URLSearchParams object
  params: {
    ID:12345
  },
  //` paramsSerializer `is an optional function that works by serializing 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 applies only to methods: `put/post/patch`
  //When the `transformRequest'option is not set, dada must be one of the following types
  //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 delayed for requests to be sent
  //If the request takes longer than the delay time, the request is terminated

  timeout:1000,
  //` The with Credentails `option indicates whether it is a cross-domain request?
  
  withCredentials:false,//default
  //` The adapter `adapter'option allows custom processing of requests, which makes testing easier
  //Returns a promise and provides a validation return
  adapter: function(config){
    /*..........*/
  },
  //` auth ` indicates that HTTP-based authentication should be used and provides certificates
  //This will set an authorization header and override 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
  //` onUpload Progress `Upload Progress'Upload Progress Event
  onUploadProgress:function(progressEvent){
    //Download progress events
onDownloadProgress:function(progressEvent){
}
  },
  //Maximum of corresponding content
  maxContentLength:2000,
  //` validateStatus ` defines whether to resolve or reject promise based on the corresponding http status code
  //If `validateStatus'returns true (or is set to `null' or `undefined'), then the state of promise will be resolved, otherwise its state 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 agent to be used 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}),
  //proxy defines the host name and port number.
  //` auth ` indicates that http basic authentication should be linked to proxy proxy proxy and provide certificates
  //This will set up a `Proxy-Authorization'header and will override the existing `Proxy-Authorization' header.
  proxy: {
    host:'127.0.0.1',
    port: 9000,
    auth: {
      username:'skda',
      password:'radsd'
    }
  },
  //` cancelToken `defines a cancel token for canceling requests
  //See the cancelation section for details.
  cancelToken: new cancelToken(function(cancel){

  })
}

V. Content of the Request Return

{

  data:{},
  status:200,
  //Return from the server http State text
  statusText:'OK',
  //Response header information
  headers: {},
  //`config`It's some configuration information at request time.
  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);
  })

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. Default settings for custom instances

//Configure default configuration when creating instances
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

  • Configuration will be merged by priority, in the order of default configuration in lib/defauts.js, default configuration in the instance, and config parameter configuration in the request. The higher the level, the later will cover 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, from the default value of libray
var instance = axios.create();
//Return to override the default value of library
//Now all requests have to wait 2.5S before they can be sent out.
instance.defaults.timeout = 2500;
//The timeout here changes from 2.5S to 5s before coverage.
instance.get('/longRequest',{
  timeout: 5000
});

Interceptors

  • You can intercept requests and responses before they reach then/catch
//Add a request interceptor
axios.interceptors.request.use(function(config){
  //Do some action 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. Adding 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 in the 2xx range?
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.header);
    }else {
      //Some errors are triggered when requests are set
      console.log('Error',error.message);
    }
    console.log(error.config);
  });

Nine, cancel

  • You can cancel a request through a cancel token
  1. You can create a cancel token through the CancelToken.source factory function
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 requests (information parameters can be set)
source.cance("operation canceled by user");

  1. 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 a parameter
    cancel = c;
  })
})
//Cancellation request
cancel();


Author: Funny Seeker
Link: https://www.jianshu.com/p/df464b26ae58
Source: Brief Book
Copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Posted by JamieinNH on Wed, 15 May 2019 15:31:43 -0700