Vue Advanced (iii): Axios use detailed
HTTP request clients based on Promise, which can be used in both browsers and Node.js. functional features send xmlhttprequests requests in browsers, HTTP requests in Node.js, support Promise APIs, intercept requests and responses, transform request and response data, convert JSON data automatically, and client support protection Ann All free from XSRF attacks; browser support; Install
Use Bower:
$ Bower Install Axios
Using NPM:
$ NPM Install Axios
Example
send a GET request
Make a request to a user with a given ID
axios.get ('/user?id=12345 ')
. Then (function (response) {
CONSOLE.L OG (response);
})
. catch (function (response) {
Console.log (response);
});
Optionally the request above could also
is done as axios.get ('/user ', {
params: {
id:12345
}
})
. Then (function (response) {
Console.log (response);
})
. catch (function (response) {
Console.log (response);
});
send a POST request
Axios.post ('/user ', {
firstName: ' Fred ',
lastName: ' Flintstone '
})
. Then (function (response) {
Console.log (response);
})
. catch (function (response) {
Console.log (response);
});
send multiple concurrent 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) {
//Both Requests are now complete
}));
You can customize the request by passing the corresponding parameter to the Axios:
Axios (config)
//Send a POST request
Axios ({method
: ' POST ',
URL: '/user/12345 ',
data: {
FirstName: ' Fred ',
lastName: ' Flintstone '
}
};
Axios (url[, config])
//sned a GET Request (default method)
Axios ('/user/12345 ');
Request Method Alias
For convenience, we provide aliases for all supported request methods.
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])
Attention
The URL, method, and data properties do not need to be specified in the config parameter when using the alias methods.
Concurrent
Help method for processing concurrent requests
Axios.all (iterable)
Axios.spread (callback)
Create an instance
You can create a new Axios instance with a custom configuration.
Axios.create ([config])
var instance = axios.create ({
baseurl: ' https://some-domain.com/api/',
timeout: 1000,
headers: {' X-custom-header ': ' Foobar '}
});
Instance method
All of the available instance methods are listed below, and the specified configuration will be merged with the configuration of the instance.
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 Configuration
The following are the available request configuration items, only the URLs are required. If method is not specified, the default request is get.
{//' URL ' is the server URL that'll be used for the request URL: '/user ',///' The request of ' method ' is used
When making the "request method": ' Get ',//default//' BaseURL ' would be prepended to ' url ' unless ' url ' is absolute.
It can be convenient to set ' BaseURL ' for a instance of Axios to pass relative the URLs//To methods of this instance. BaseURL: ' https://some-domain.com/api/',//' transformrequest ' allows changes to the request data before it are sent to th E Server//This are only applicable for request methods ' put ', ' POST ', and ' PATCH '//The last function in the array must Return a string or a arraybuffer transformrequest: [function (data) {//does whatever you want to transform the data retu
RN data; }],///' Transformresponse ' allows changes to the response data to being made before//it is passed to Then/catch Esponse: [function (data) {//do whatever your want to transform the data return data}],//' headers ' are custom Heade RS to is sent HeadeRS: {' X-requested-with ': ' XMLHttpRequest '},//' params ' are the URL parameters to is sent with the request params: {ID: 12345},///' Paramsserializer ' is a optional function in charge of serializing ' params '//(e.g. https://www.npmjs.com/p Ackage/qs, http://api.jquery.com/jquery.param/) paramsserializer:function (params) {return qs.stringify (params, { Arrayformat: ' Brackets '}},//' data ' is the ' the ' of the data to be sent as the request body//Only applicable for request methods ' Put ', ' POST ', and ' PATCH '//When no ' transformrequest ' is set, must being a string, an arraybuffer or a hash data: {FIRSTN
Ame: ' Fred '},///' timeout ' specifies the number of milliseconds before the request times out.
If the request takes longer than ' timeout ', the request would be aborted. timeout:1000,//' withcredentials ' indicates whether or not cross-site Access-control-requests//should be made using C Redentials withcredentials:false,//default//' adapter ' allows custom handling of requests which MAKES testing easier.
Call ' resolve ' or ' reject ' and supply a valid response ([Response docs] (#response-api)). Adapter:function (resolve, reject, config) {/* ... */},//' auth ' indicates that HTTP Basic auth should is used, and s
Upplies credentials. This is set a ' Authorization ' header, overwriting any existing//' Authorization ' custom headers you have set using
' Headers '. Auth: {username: ' janedoe ', Password: ' S00pers3cret '}//' Responsetype ' indicates ' the type of data that the server would Respond with//options are ' arraybuffer ', ' blob ', ' document ', ' json ', ' text ' Responsetype: ' json ',//default//' XSRFC Ookiename ' is the name of the cookie to use as a value for XSRF token xsrfcookiename: ' Xsrf-token ',//default//' XSRFHE Adername ' is the name of the HTTP header that carries the XSRF token value xsrfheadername: ' X-xsrf-token ',//default// ' Progress ' allows handling of progress events for ' POST ' and ' put uploads '//As a ' get ' downloads progress:functiOn (progressevent) {//does whatever you want with the native Progress event}}
data structure of the response
The data for the response includes the following information:
{
//' data '
is the response this is provided by the server data: {},
//' status ' is the HTTP status code from The server response
status:200,
//' StatusText ' is the HTTP status message from the server response
Statuste XT: ' OK ',
//' headers ' the headers that's the server responded
with headers: {},
//' config ' was the config that was provided to ' Axios ' for the Request
Config: {}
}
When using then or catch, you receive the following response:
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);
});
Default configuration
You can specify a default configuration for each request. Global Axios Default configuration
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 ';
Custom Instance default configuration
Set config defaults when creating the instance
var instance = axios.create ({
baseurl: ' https://api.example.com '
});
Alter defaults After instance has been created instance.defaults.headers.common[' Authorization
' = Auth_token;
priority order of configuration
Config'll is merged with a order of precedence. The order was library defaults found in Lib/defaults.js, then defaults property of the instance, and finally config Argumen T for the request. The latter'll take precedence over the former. Here's an example.
Create A instance using the config defaults provided by the the library//At this point the
Timeout config value is ' 0 ' as is the default for the library
var instance = axios.create ();
Override timeout default for the library/now all requests'll wait 2.5 seconds before timing out
INSTANCE.D Efaults.timeout = 2500;
Override timeout for this request as it's known to take a long time
instance.get ('/longrequest ', {
timeout:500 0
Intercepting Device
Add Interceptor
You can intercept requests and responses before handling then or catch
Add a Request Interceptor
axios.interceptors.request.use (function (config) {
//do something before request is sent
return config;
}, Function (Error) {
//does something with request error return
Promise.reject (error);
});
//Add a response Interceptor
axios.interceptors.response.use (function (response) {
//do something with response data Return
response
}, function (Error) {
//does something with response error return
Promise.reject ( Error);
Removing an interceptor
var myinterceptor = Axios.interceptors.request.use (function () {/*...*/});
Axios.interceptors.request.eject (Myinterceptor);
You can add interceptors to a custom Axios instance:
var instance = axios.create ();
Instance.interceptors.request.use (function () {/*...*/});
Error handling
Axios.get ('/user/12345 ')
. catch (function (response) {
if (response instanceof Error) {
//something Happened in setting up the request that triggered a Error
console.log (' Error ', response.message);
} else {
/ The request was made, but the server responded with a status code
//That falls out of the range of 2xx
CONSOLE.L OG (response.data);
Console.log (response.status);
Console.log (response.headers);
Console.log (Response.config);
}
);
promises
Axios relies on a native ES6 Promise implementation, and if your browser environment does not support ES6 promises, you need to introduce Polyfill typescript
Axios contains a typescript definition
<reference path= "axios.d.ts"/>
import * as Axios from ' Axios ';
Axios.get ('/user?id=12345 ');
Credits
Axios is heavily inspired by the httpserviceprovidedinangular.ultimately