axios

directory

  • axios
    • The body of the
    • The original
    • features
    • Browser support
    • The installation
    • The sample
    • axios API
    • Alias of the request method.

The installation

Use NPM:

$ npm i axios
Copy the code

Use the bower

$ bower instal axios
Copy the code

Use the CDN

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

The sample

Make a GET request

Const axios = require('axios') // initiate a user request with the given ID axios.get('/user? ID=12345') .then(function(respone){ console.log(response); }) .catch(function(error){ console.log(error); }); Get ('/user',{params:{ID:12345}}). Then (function(response){console.log(response); }).catch(function(error){ console.log(error) });Copy the code

Note: Async /await is the syntax of ECMAScript2017, ie and some older browsers do not support it, please use with caution. (Ts is easy to compile and use, and does not require any spacers. The target is es5.)

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(){ return axios.get('/user/12345'); } function getUserPermissions(){ return axios.get('/user/12345/permissions'); } axios.all([getUerAccount(),getUserPermissions()]).then(axios.spread(function(acc,pers){// Both requests are now complete}));Copy the code

Translator: Becauseaxios.allIt’s similarPrimise.allIf there is an error in one of the requests, the request will be stopped. Therefore, it is recommended to attach a catch to a single request.

axios API


You can pass some Settings to Axios to generate a Request based on your needs.

axios(config)

// Make a POST request axios({method:' POST ',// method URL :'/user/12345',// address data:{// parameters firstName:'Fred', lastName:'Flintstone'}}); 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

Alias of the request method.

For convenience, Axios provides alias support for all request 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

Url,method, and data attributes do not have to be explicitly specified in config when using alias methods (as in the post method request in the example above).

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 of the instance methods available are listed below, and the specific Settings will be applied in the instance.

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

Requeset 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 to request the URL :'/user', // 'method' is the method used to initiate the request method: 'get ', //' baseURL 'if the' url 'is not an absolute address, it will be preceded by it. // It is convenient to set 'baseUrl' on axios instances with relative addresses. 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', 'POST', 'PATCH' methods. // The last function in the array must return either a string or an 'ArrayBuffer', or a 'Stream', 'Buffer' instance, 'ArrayBuffer', 'FormData' // You may also need to set headers TransformRequest :[function(data,headers){return data; }], // 'transformResponse' allows processing of returned data before passing it to then/catch :[function(data){// Processing of returned data as required; }], // headers:{' x-requested-with ':'XMLHttpRequest'}, // params' is a request parameter in the request connection. It must be a pure object. Or URLSearchParams object params:{ID:12345}, // 'paramsSerializer' is an optional function used to control and serialize parameters // for example: (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 is used as the body of the request // Only applies to the application 'PUT','POST','PATCH', request method // When 'transformRequest' is not set, it must be one of the following types (non-returnable?) : / / - string (string), plain object (pure object), ArrayBuffer, ArrayBufferView, URLSearchParams / / - limit the browser: FormData,File,Blob //- limit Node: Stream data:{firstName:' Fred '}, // 'timeout' defines the request time in milliseconds. // If the request time exceeds this set time, the request will stop. Timeout :1000, // 'withCredentials' indicates whether cross-domain requests require proof. WithCredentials :false // Default value // adapter Adapters that allow custom handling of requests, which makes testing easier. // Return a promise and provide a valid response. (View [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 type returned by the server, These types of Settings should be //' arrayBuffer ','blob','document','json','text',stream' responseType :'json', //' responseEncoding 'to indicate parsing the corresponding encoding.  //** note that ** ignores requests whose responseType is stream or client. ResponseEncoding :'utf8'// default // 'xsrfCookieName' specifies the name of the XSRF session cookie. XsrfCookieName :' xsrF-token ',// default // 'xsrfHeaderName' is the name of the HTTP header that carries the XSRF value xrsfHeadername:' x-xsrF-token ', // Default values // 'onUploadProgress' allows process events to handle the upload process onUploadProgress: Function (progressEvent){// what you want to do when a local process event happens}, // 'onDownloadProgress' allows the process event onDownloadProgress to handle the download process: Function (progressEvent){}, // 'maxContentLength' defines the maximum size of the content returned from HTTP. 2000, // 'validateStatus' defines promise resolve and reject. // HTTP returns a status code. If 'validateStatus' returns true (or null/undefined), the Promise will resolve; Other promises will reject. validateStatus: function(status){ return status >= 200 && stauts < 300; // Default}, // maxRedirect defines the maximum number of redirects to Node.js. // If the value is 0, there is no redirect. MaxREdirects :5,// default // 'socketPath' defines a 'UNIX Socket' used in Node.js. // For example, '/var/run/docker.sock' sends requests to the Docker daemon. // 'socketPath' and 'proxy' can only be defined. // Only 'socketPath' will be used if both are defined. SocketPath :null,// default // 'httpAgent' and 'httpsAgent' define a custom proxy when an HTTP or HTTPS request is generated, 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 host name and port number of the server. // '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.0.1, port:9000, auth:{username:' CDD ', password:'123456'}}, // 'cancelTaken' CancelToken: new cancelToken (function(cancel){})}Copy the code

Returns the Response Schema

The return of a request contains the following information

Data {}, // 'status' is the HTTP status code returned by the server, //' statusText 'is the HTTP status information returned by the server statusText: Headers :{}, // 'config' is set to axios, Config :{} // 'request' is used to retrieve the current request // it is the last instance of ClientRequest in Node.js (in redirect). // Or XMLHttpREquest instance in the browser}Copy the code

When you use then, you receive the following message:

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 processed.


Default Settings (Config Default)

You can set a default setting that will take effect on each subsequent request.

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 instance = axios.create({baseURL:'https://api.example.com'}); / / or 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) are merged in priority order. 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