版本 v0.19.0node
axios 是基於Promise的http庫,可運行於瀏覽器和node客戶端。jquery
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
支持 | 支持 | 支持 | 支持 | 支持 | ie8+ |
ie8,ie9須要先解決瀏覽器不支持跨域問題,其餘瀏覽器無歷史問題不須要擔憂兼容問題。ios
npmes6
$ npm install axios
複製代碼
cdndocker
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
複製代碼
axios使用通常分爲兩種,直接使用和建立實例後使用。爲了保持項目的可擴展、純粹項目中咱們通常採用實例化使用。npm
import axios from 'axios'
axios({
method: 'post',
url: '/user/12345',
data: { //'post', 'put', 'patch'方法支持攜帶data,其餘方法不支持
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(function(response) {
console.log(response)
}
複製代碼
axios.request與axios(cofing)用法相同
其他7種方法分別表明http的7種請求方法( 'post', 'put', 'patch'方法支持攜帶data,其餘方法不支持 )編程
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
複製代碼
var instance = axios.create({
baseURL: 'https://some-domain.com/api/', //設置根url
timeout: 1000, //超時時間
headers: {'X-Custom-Header': 'foobar'} //請求頭
});
複製代碼
使用方法與直接使用相同,一樣擁有8種方法。json
axios.all(iterable)
axios.spread(callback)
複製代碼
axios.all源碼以下,在這裏要求參數是一個axios組成的數組axios
axios.all = function all(promises) {
return Promise.all(promises);
};
複製代碼
axios.spread源碼以下,是利用函數式編程須要第二個參數輸入一個axios組成的數組api
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
複製代碼
Request Config 請求配置
{
//`url`是服務器連接,用來請求
url:'/user',
//`method`是發起請求時的方法
method:`get`,
//`baseURL`若是`url`不是絕對地址,那麼將會加在其前面。
//能夠很方便的對相對地址的axios實例設置`baseUrl`。
baseURL:'http://some-domain.com/api/',
//`transformRequest`容許請求的數據在發送至服務器以前進行轉化。
//這個只適用於`PUT`,`GET`,`PATCH`方法。
//數組中的最後一個函數必須返回一個字符串或者一個`ArrayBuffer`,或者`Stream`,`Buffer`實例,`ArrayBuffer`,`FormData`
//此外你也可能須要設置下headers對象
transformRequest:[function(data,headers){
//依本身的需求對請求數據進行處理
return data;
}],
//`transformResponse`容許對返回的數據傳入then/catch以前進行處理
transformResponse:[function(data){
//依須要對數據進行處理
return data;
}],
//`headers`是自定義的要被髮送的信息頭
headers:{'X-Requested-with':'XMLHttpRequest'},
//`params`是請求鏈接中的請求參數,必須是一個純對象,或者URLSearchParams對象
params:{
ID:12345
},
//`paramsSerializer`是一個可選的函數,用來控制和序列化參數
//例如:(https://ww.npmjs.com/package/qs,http://api.jquery.com/jquery.param/)
paramsSerializer: function(params){
return Qs.stringify(params,{arrayFormat:'brackets'})
},
//`data`是請求時做爲請求體的數據
//只適用於應用的'PUT','POST','PATCH',請求方法
//當沒有設置`transformRequest`時,必須是如下其中之一的類型(不可重複?):
//-string(字符串),plain object(純對象),ArrayBuffer,ArrayBufferView,URLSearchParams
//-限瀏覽器:FormData(表格數據),File(文件數據),Blob
//-限Node:Stream
data:{
firstName:'fred'
},
//`timeout`定義請求的時間,單位是毫秒。
//若是請求的時間超過這個設定時間,請求將會中止。
timeout:1000,
//`withCredentials`代表跨跨域請求書否須要證實。
withCredentials:false //默認值
//`adapter`適配器,容許自定義處理請求,這會使測試更簡單。
//返回一個promise,而且提供一個有效的相應。(查看[response docs](#response-api))
adapter:function(config){
/*...*/
},
//`auth`代表HTTP基礎的認證應該被使用,而且提供證書。
//這個會設置一個`authorization` 頭(header),而且覆蓋你在header設置的Authorization頭信息。
auth:{
username:'janedoe',
password:'s00pers3cret'
},
//`responsetype`代表服務器返回的數據類型,這些類型的設置應該是
//'arraybuffer','blob','document','json','text','stream'
responsetype:'json',
//`responseEncoding`代表解析相應的編碼方式。
//**注意**會忽視responseType爲stream或者客戶端的請求。
responseEncoding:'utf8'//默認值
//`xsrfCookieName`時cookie作xsrf會話時的名字。
xsrfCookieName:'XSRF-TOKEN',//默認值
//`xsrfHeaderName` 是http頭(header)的名字,而且該頭攜帶xsrf的值
xrsfHeadername:'X-XSRF-TOKEN',//默認值
//`onUploadProgress`容許處理上傳過程的進程事件
onUploadProgress: function(progressEvent){
//本地過程事件發生時想作的事
},
//`onDownloadProgress`容許處理下載過程的進程事件
onDownloadProgress: function(progressEvent){
//下載過程當中想作的事
},
//`maxContentLength` 定義http返回內容的最大字節容量
maxContentLength: 2000,
//`validateStatus` 定義promise的resolve和reject。
//http返回狀態碼,若是`validateStatus`返回true(或者設置成null/undefined),promise將會resolve;其餘的promise將reject。
validateStatus: function(status){
return status >= 200 && stauts < 300;//默認
},
//`maxRedirect`定義重導向到node.js中的最大數量。
//若是值爲0,那麼沒有redirect。
maxREdirects:5,//默認值
//`socketPath`定義一個在node.js中使用的 `UNIX Socket`。
//例如 `/var/run/docker.sock`發送請求到docker daemon。
//`socketPath`和`proxy`只可定義其一。
//若是都定義則只會使用`socketPath`。
socketPath:null,//默認值
//`httpAgent` 和 `httpsAgent`當產生一個http或者https請求時分別定義一個自定義的代理,在nodejs中。
//這個容許設置一些選選個,像是`keepAlive`--這個在默認中是沒有開啓的。
httpAgent: new http.Agent({keepAlive:treu}),
httpsAgent: new https.Agent({keepAlive:true}),
//`proxy`定義服務器的主機名字和端口號。
//`auth`代表HTTP基本認證應該跟`proxy`相鏈接,而且提供證書。
//這個將設置一個'Proxy-Authorization'頭(header),覆蓋原先自定義的。
proxy:{
host:127.0.0.1,
port:9000,
auth:{
username:'cdd',
password:'123456'
}
},
//`cancelTaken` 定義一個取消,可以用來取消請求
//(查看 下面的Cancellation 的詳細部分)
cancelToken: new CancelToken(function(cancel){
})
}
複製代碼
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';
複製代碼
// 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;
複製代碼
在多處設置配置後,最終配置將合併。優先級以下:
/使用默認庫的設置建立一個實例,
//這個實例中,使用的是默認庫的timeout設置,默認值是0。
var instance = axios.create();
//覆蓋默認庫中timeout的默認值
//此時,全部的請求的timeout時間是2.5秒
instance.defaults.timeout = 2500;
//覆蓋該次請求中timeout的值,這個值設置的時間更長一些
instance.get('/longRequest',{
timeout:5000
});
複製代碼
以在請求或者返回被then或者catch處理以前對他們進行攔截。
/添加一個請求攔截器
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);
});
複製代碼
刪除一個攔截器
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
複製代碼
實例中使用攔截器
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
複製代碼
axios.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 if(error.request){
//若是是請求時的錯誤,且沒有收到相應
//`error.request`是一個瀏覽器的XMLHttpRequest實例,或者node.js的 ClientRequest實例。
console.log(error.request)
}
else{
//一些錯誤是在設置請求時觸發的
console.log('Error',error.message);
}
console.log(error.config);
});
複製代碼
可使用cancel token取消一個請求
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
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
複製代碼
能夠給CancelToken構造函數傳遞一個executor function來建立一個cancel token:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
複製代碼
默認狀況下,axios串聯js對象爲JSON格式。爲了發送application/x-wwww-form-urlencoded格式數據, 你可使用一下的設置。
瀏覽器中可使用 URLSearchParams API 以下:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
複製代碼
URLSearchParams是es6新的API,兼容須要增長 polyfill
使用qs格式化數據
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
複製代碼
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
複製代碼