axios是基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端;可以用在webpack + vuejs 的項目中
原文 https://github.com/axios/axios
1、example
1.1、get請求
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);
});
//從遠程獲取圖片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
1.2、post請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
因axios post數據采用的是 Content-Type: 'application/x-www-form-urlencoded',所以后端是接受不到json格式的數據的
解決方法:引入qs庫,發送請求之前將數據qs.stringify(data),是為了將數據變成類似title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3這種格式
1.2.1. application/x-www-form-urlencoded
POST http://www.example.com HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=utf-8
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
1.2.2 form-data
POST http://www.example.com HTTP/1.1
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="text"
title
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png
PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--
1.2.3 application/json
POST http://www.example.com HTTP/1.1
Content-Type: application/json;charset=utf-8
{"title":"test","sub":[1,2,3]}
1.2.4 text/xml
POST http://www.example.com HTTP/1.1
Content-Type: text/xml
<!--?xml version="1.0"?-->
<methodcall>
<methodname>examples.getStateName</methodname>
<params>
<param>
<value><i4>41</i4></value>
</param>
</params>
</methodcall>
>
1.3、並發請求
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) {
}));
2 API
2.1 發送請求配置config
{
url:'/user',
method:`get`,
//`baseURL`如果`url`不是絕對地址,那么將會加在其前面,當axios使用相對地址時這個設置非常方便
baseURL:'http://some-domain.com/api/',
//`transformRequest`允許請求的數據在傳到服務器之前進行轉化。
//這個只適用於`PUT`,`GET`,`PATCH`方法。
//數組中的最后一個函數必須返回一個字符串或者一個`ArrayBuffer`,或者`Stream`,`Buffer`實例,`ArrayBuffer`,`FormData`
transformRequest:[function(data){
//依自己的需求對請求數據進行處理
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:{
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',
//`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將會接受;其他的promise將會拒絕。
validateStatus: function(status){
return status >= 200 && stauts < 300;//默認
},
//`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){
})
}
//reponse 應該包括的內容
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}
2.2 獲取數據request方法
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]])
2.3 攔截
//發送request之前
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);
});