axios

Version: v0.16.1

Promise is based on HTTP clients for browsers and NodeJS

The original

Click to view the original article

features

  • The browser initiates the XMLHttpRequests request
  • The Node sends an HTTP request
  • Supporting Promise API
  • Intercept requests and returns
  • Converting requests and returning (data)
  • Cancel the request
  • Automatically convert JSON data
  • Client support against XSRF (Cross-site request Forgery)

The installation

Use NPM:



$ npm i axiosCopy the code

Use the bower



$ bower instal axiosCopy the code

Use the CDN



<! - domestic bootCDN -- -- >
<script src="https://cdn.bootcss.com/axios/0.16.0/axios.min.js"></script>Copy the code

The sample

Make a GET request



// Initiate a user request with the given ID
axios.get('/user? ID=1234').then(function(respone){
    console.log(response); }).catch(function(error){
    console.log(error);
});

// The above request can also be written in the following way
axios.get('/user',{
    params:{
        ID:12345}}).then(function(response){
        console.log(response); }).catch(function(error){
        console.log(error)});Copy the code

Make a POST request



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

Initiate multiple concurrent requests



function getUserAccount(a){
    return axios.get('/user/12345');
}

function getUserPermissions(a){
    return axios.get('/user/12345/permissions');
}

axios.all([getUerAccount(),getUserPermissions()])
    .then(axios.spread(function(acc,pers){
        // Both requests are now complete
    }));Copy the code

axios API


There are some Settings you can make to AxiOS to generate the request.

axios(config)



// Initiate a POST request

axios({
    method:'post'./ / method
    url:'/user/12345'./ / address
    data: {/ / parameters
        firstName:'Fred'.lastName:'Flintstone'}});Copy the code


// Get the remote image by request
axios({
    method:'get'.url:'http://bit.ly/2mTM3Ny'.responseType:'stream'
})
    .then(function(response){
        response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))})Copy the code

axios(url[,config])



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

Request a rename of the method.

For convenience, Axios provides renaming support for all requested methods

axios.request(config)

axios.get(url[,config])

axios.delete(url[,config])

axios.head(url[,config])

axios.options(url[,config])

axios.post(url[,data[,config]])

axios.put(url[,data[,config]])

axios.patch(url[,data[,config]])

Pay attention to

The URL,method, and data attributes do not need to be specified in config when renaming methods.

Concurrent Concurrency

Useful method

axios.all(iterable)

axios.spread(callback)

Create an instance

You can create a new instance using custom Settings

axios.create([config])



var instance = axios.create({
    baseURL:'http://some-domain.com/api/',
    timeout:1000,
    headers:{'X-Custom-Header':'foobar'}
});Copy the code

Instance methods

Some example methods are listed below. The specific Settings will be merged in the instance Settings.

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

Requese Config Request Settings

Below are some of the options for setting the request. Only the URL is required, and if method is not specified, the default request method is GET.



{
    // 'url' is the server link used for the request
    url:'/user'.// 'method' is the request method when the request is initiated
    method:`get`,

    // 'baseURL' will be preceded if the url is not an absolute address.
    // This is handy when Axios uses relative addresses
    // The method in the example
    baseURL:'http://some-domain.com/api/'.// 'transformRequest' allows requested data to be transformed before being sent to the server.
    // This applies only to the 'PUT', 'GET', 'PATCH' methods.
    // The last function in the array must return either a string or an ArrayBuffer, or a Stream, an instance of Buffer, ArrayBuffer, FormData
    transformRequest:[function(data){
        // Process the requested data according to your own requirements
        returndata; }].// 'transformResponse' allows returned data to be processed before it is passed to then/catch
    transformResponse:[function(data){
        // Process the data as needed
        returndata; }].// 'headers' is a custom header to be sent
    headers:{'X-Requested-with':'XMLHttpRequest'},

    // 'params' is the request parameter in the request connection and must be a pure object or URLSearchParams object
    params:{
        ID:12345
    },
    
    // 'paramsSerializer' is an optional function that is used to serialize parameters
    / / such as: (https://ww.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
    paramsSerializer: function(params){
        return Qs.stringify(params,{arrayFormat:'brackets'})},// 'data' is the data that needs to be set for the request
    // Apply only to application 'PUT','POST','PATCH' request methods
    // When 'transformRequest' is not set, it must be one of the following types (non-repeatable?) :
    //-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams
    //- Browser only: FormData,File,Blob
    //- only Node: Stream
    data:{
        firstName:'fred'
    },
    // 'timeout' defines the time of the request in milliseconds.
    // If the request time exceeds this set time, the request will stop.
    timeout:1000.// 'withCredentials' indicates whether the protocol is accessed across websites,
    // Certificates should be used
    withCredentials:false / / the default value

    // Adapter adaptor, which allows custom processing of requests, which makes testing easier.
    // Return a promise and provide validation returns (see [Response docs](#response-api))
    adapter:function(config){
        / *... * /
    },

    // 'auth' indicates that HTTP-based authentication should be used and certificates provided.
    // This sets an authorization header and overrides the authorization header you set in the header.
    auth:{
        username:'janedoe',
        password:'s00pers3cret'
    },

    // 'responseType' indicates the data types returned by the server. These types should be set to
    //'arraybuffer','blob','document','json','text',stream'
    responsetype:'json'.// 'xsrfHeaderName' is the name of the HTTP header that carries the value of XSRF
    xrsfHeadername:'X-XSRF-TOKEN'./ / the default value

    // 'onUploadProgress' allows handling of events in the upload process
    onUploadProgress: function(progressEvent){
        // What you want to do when a local process event occurs
    },

    // 'onDownloadProgress' allows handling of events during the download process
    onDownloadProgress: function(progressEvent){
        // What you want to do during the download
    },

    // 'maxContentLength' defines the maximum amount of HTTP content to return
    maxContentLength: 2000.// 'validateStatus' defines resolve and reject for promises.
    // HTTP returns a status code. If 'validateStatus' returns true (or null/undefined), PROMISE will accept. Other promises will be rejected.
    validateStatus: function(status){
        return status >= 200 && stauts < 300;/ / the default
    },

    // 'httpAgent' and 'httpsAgent' define a custom proxy for an HTTP or HTTPS request, respectively, in nodeJS.
    // This allows setting a few options, such as' keepAlive '- this is disabled by default.
    httpAgent: new http.Agent({keepAlive:treu}),
    httpsAgent: new https.Agent({keepAlive:true}),

    // 'proxy' defines the server host name and port number.
    // 'auth' indicates that HTTP basic authentication should be connected to 'proxy' and provide a certificate.
    // This will set a 'proxy-authorization' header, overwriting the original custom.
    proxy:{
        host:127.0. 01.,
        port:9000,
        auth:{
            username:'cdd',
            password:'123456'}},// 'cancelTaken' defines a cancellation that can be used to cancel the request
    // (See the details of The Cancellation below)
    cancelToken: new CancelToken(function(cancel){})}Copy the code

Returns the Response Schema

The return of a request contains the following information



{
    //`data`Is the reply (as opposed to the request) provided by the server data{},//`status`Is the HTTP status code returned by the serverstatus:200.//`statusText`Is HTTP status information returned by the serverstatusText: 'ok'.//`headers`Is the HEADERS carried in the server returnheaders:{},

    //`config`Is set to Axios for requestconfig:{}}Copy the code

Using then, you receive the following information



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

When a catch is used, or a Reject callback is passed as the second argument to a THEN, the returned error message can be used.


Default Settings (Config Default)

You can set a default setting that will work on all requests.

The Global default setting is Global AXIOS Defaults



axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';Copy the code

Example Custom instance default



Var is set by default when creating an instance instance = axios.create({ baseURL:'https://api.example.com' }); / / change the default value after the instance creation instance.defaults.headers.com mon [' Authorization '] = AUTH_TOKEN;Copy the code

Run the Config order of precedence command to set precedence

The Settings (Config) will be consolidated in order of priority. The first is the default Settings defined in lib/defaults.js, the second is the Settings of the defaults instance properties, and the last is the Settings of the config parameters in the request. The higher the level, the higher the level, overrides the previous Settings. Look at this example:



// Create an instance using the default library Settings. // In this instance, use the default library timeout setting, which defaults to 0. var instance = axios.create(); / / override the default repository timeout defaults / / at this point, all the request timeout time is 2.5 second instance. Defaults. Timeout = 2500; Instance. get('/longRequest',{timeout:5000});Copy the code

The interceptor interceptors

You can intercept requests or returns before they are processed by then or catch.



// Add a request interceptor
axios.interceptors.request.use(function(config){
    Do something before the request is sent
    return config;
},function(error){
    // Do something when a request error occurs
    return Promise.reject(error);
});

// Add a return interceptor
axios.interceptors.response.use(function(response){
    // Do some processing on the returned data
    return response;
},function(error){
    // Do some processing for the returned error
    return Promise.reject(error);
});Copy the code

If you need to remove the interceptor later, you can



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

You can use interceptors in an axios instance



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

Handling Errors



axios.get('user/12345').catch(function(error) {if(error.response){
            // There is a request, but the server returns a status code
            // They are all outside 2xx
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
        }else{
            // Some errors are triggered when setting up the request
            console.log('Error'.error.message);
        }
        console.log(error.config);
    });Copy the code

You can customize the error range of the HTTP status code using the validateStatus setting option.



axios.get('user/12345',{
    validateStatus:function(status){
        return status < 500;If the return code is less than or equal to 500, it is an error}});Copy the code

Cancel the Cancellation

You can cancel a request using the Cancel token



The axioscancel tokenThe API is based on ** CNacelable Promises Proposal **, which is currently in the first phase.Copy the code

You can create a cancel token using the canceltoken. source factory function as follows:



var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
    cancelToken:source.toke
}).catch(function(thrown){
    if(axiso.isCancel(thrown)){
        console.log('Rquest canceled', thrown.message);
    }else{
        //handle error}});// Cancel the request (info parameter setting is configurable)
source.cancel("Operation cancelled by user");Copy the code

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 executor(c){
        // This executor function takes a cancel function as an argumentcancel = c; })});// Cancel the request
cancel();Copy the code


Note: You can use the samecancel tokenCancel multiple requests.Copy the code

Use Application/X-www-form-urlencoded formatting

By default, AXIos concatenates JS objects in JSON format. To send Application/X-WWw-form-urlencoded data, you can use the following Settings.

The Browser Browser

In the browser you can use the URLSearchParams API as follows:



var params = new URLSearchParams();
params.append('param1'.'value1');
params.append('param2'.'value2');
axios.post('/foo'.params);Copy the code

Note: URLSearchParams does not support all browsers, but there is a poly fill available (make sure the shipper is in the browser global environment)

Other methods: You can use the QS library to format data.



var qs = require('qs');
axios.post('/foo', qs.stringify({'bar':123}));Copy the code

Node.js

In NodeJS, you can use queryString as follows:



var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({foo:'bar'}));Copy the code

You can also use the QS library.


promises

Axios is based on the native ES6 Promise implementation. Use gaskets if the environment does not support them.

TypeScript

Axios contains TypeScript definitions



import axios from 'axios'
axios.get('/user? ID=12345')Copy the code

Special paper

  • Cross-domain development using AXIos.
  • Cooperate with Axios to learn promise. Uploaded soon, please look forward to…