Axios is a promise-based HTTP library that supports blocking requests and responses, automatically converting JSON data, and clients supporting defenses? XSRF.
# # Installation
Using NPM:
$ npm install axios
# # GET
There are two ways of performing a GET request:
// 为给定 ID 的 user 创建请求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
// 可选地,上面的请求可以这样做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
# # POST
Perform a POST request
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error);
Executing 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) { // 两个请求现在都执行完成 }));
# # Axios API
You can create requests by passing related configurations to Axios
Axios (config)
// 发送 POST 请求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
Axios (url[, config])
// 发送 GET 请求(默认的方法)axios('/user/12345');
Alias of the Request method
为方便起见,为所有支持的请求方法提供了别名#### 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]])
Creating an instance you can use a custom configuration to create a new Axios instance axios.create ([config])
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
# # Request Configuration Overview
These are the configuration options that can be used when creating the request. Only URLs are required. If no method is specified, the request defaults to the Get method.
' URL ' is the URL of the server URL used for the request: '/user ',//' method ' is the way to create the request: ' Get ',//The default is get//' BaseURL ' will be automatically added to the ' URL ' before, unless ' URL ' is an absolute URL. It is possible to pass a relative URL BaseURL by setting a ' BaseURL ' method for Axios instances: ' https://some-domain.com/api/',//' Transformrequest ' allows the service Before sending, modify the request data//can only be used in ' PUT ', ' POST ' and ' PATCH ' several request methods//After the function in the array must return a string, or ArrayBuffer, or Stream transformrequest: [function (data) {//Any conversion of data to process the return data; }],//' Transformresponse ' allows the response data to be modified before it is passed to Then/catch transformresponse: [function (data) {//Arbitrary conversion processing of data return data; }],//' headers ' is the custom request header that is about to be sent headers: {' x-requested-with ': ' XMLHttpRequest '},//' params ' is the URL parameter that will be sent with the request Must be an unformatted object (plain objects) or Urlsearchparams object params: {id:12345},//' Paramsserializer ' is a responsible ' params ' serialized function//(e.g. Https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) Paramsserializer : function (params) {RetuRN Qs.stringify (params, {arrayformat: ' brackets '})},//' data ' is sent as the principal of the request///Only applicable to these request methods ' PUT ', ' POST ', and ' PAT ' CH '//Must be one of the following types when no ' Transformrequest ' is set://-string, plain object, ArrayBuffer, Arraybufferview, Urlsearchparam S//-browser Exclusive: FormData, File, Blob//-Node Exclusive: Stream data: {firstName: ' Fred '},//' timeout ' specified please The number of milliseconds to timeout (0 for no time-out)//If the request has exceeded ' timeout ', the request will be interrupted timeout:1000,//' withcredentials ' indicates whether credentials are required for cross-domain requests Withcredentials:false,//default//' adapter ' allows custom processing requests to make testing easier//return a promise and apply a valid response (see [Response docs] (#response-api)). Adapter:function (config) {/* ... */},//' auth ' indicates that HTTP Basic authentication should be used and provide credentials//this will set a ' Authorization ' header, overwrite the existing Any use of ' headers ' set Custom ' Authorization ' header auth: {username: ' janedoe ', Password: ' S00pers3cret '}, ' Responsetype ' indicates the data type of the server response, can be ' arraybuffer ', ' blob ', ' document ', ' json ', ' text ', ' stream ' resPonsetype: ' json ',//' Xsrfcookiename ' is the name of the cookie used as the value of XSRF token xsrfcookiename: ' Xsrf-token ',//default// ' Xsrfheadername ' is the name of the HTTP header that hosts the value of XSRF token xsrfheadername: ' X-xsrf-token ',//' onuploadprogress ' allows the progress event to be processed for upload Onuploadprogress:function (progressevent) {//handling of native progress events},//' ondownloadprogress ' allows progress events to be processed for download Ondown Loadprogress:function (progressevent) {//handling of native progress events},//' maxcontentlength ' defines the maximum size allowed for the response content Maxcontentlen gth:2000,//' validatestatus ' definition for a given HTTP response status code is resolve or reject promise. If ' validatestatus ' returns ' true ' (or set to ' null ' or ' undefined '), promise will be resolve; Otherwise, promise will be rejecte validatestatus:function (status) {return status >= && status < 300;//default },//' maxredirects ' defines the maximum number of redirects follow in node. js//If set to 0, will not follow any redirect maxredirects:5,///' Httpagent ' and ' httpsagent ' are used in node. js to define custom proxies to use when executing HTTP and HTTPS. Allow configuration options like this://'KeepAlive ' Httpagent:new http is not enabled by default. Agent ({keepalive:true}), Httpsagent:new https. Agent ({keepalive:true}),//' proxy ' defines the host name and port of the proxy server//' auth ' means that HTTP Basic authentication should be used for the connection Broker and provide credentials//this will set a ' Proxy-aut Horization ' header, overwrite the existing custom ' Proxy-authorization ' header set by using ' header '. Proxy: {host: ' 127.0.0.1 ', port:9000, Auth:: {username: ' mikeymike ', Password: ' rapunz3l ' }},//' Canceltoken ' specifies the cancel token for canceling the request//(see cancellation later in this section for more) Canceltoken:new Canceltoken (function (cancel) {})}
# # # Interceptor
Intercept requests or responses before they are either then or catch processing.
// 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(function (response) { // 对响应数据做点什么 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); });
If you want to remove the interceptor later, you can:
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
Can add interceptors for custom Axios instances
var instance = Axios.create ();
Instance.interceptors.request.use (function () {/... /});
Error handling
xios.get('/user/12345') .catch(function (error) { if (error.response) { // 请求已发出,但服务器响应的状态码不在 2xx 范围内 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });
You can use the Validatestatus configuration option to define an error range for a custom HTTP status code.
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // 状态码在大于或等于500时才会 reject } })
# # Cancel
Axios's Cancel token API is based on cancelable promises proposal, which is still in its first phase.
You can use the Canceltoken.source factory method to create a cancel token, like this:
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 { // 处理错误 } }); // 取消请求(message 参数是可选的) source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing a executor function to the Canceltoken constructor:
var CancelToken = axios.CancelToken; var cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // executor 函数接收一个 cancel 函数作为参数 cancel = c; }) }); // 取消请求 cancel();
Axios Easy Tutorial