前端獲取post請求返回數據,axios傳參的幾種格式,簡書看到的技術文檔,非常詳細解釋了axios技術,值得收藏
鏈接:
//www.jianshu.com/p/df464b26ae58
一、安裝
1、 利用npm安裝(zhuang)npm install axios --save
2、 利(li)用bower安(an)裝bower install axios --save
3、 直接利用cdn引入<script src="
//unpkg.com/axios/dist/axios.min.js"></script>
二、例子
1、 發送一個GET請求
//通過給定的ID來發送請求 axios.get('/user?ID=12345') .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); }); //以上請求也可以通過這種方式來發送 axios.get('/user',{ params:{ ID:12345 } }) .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); });
2、 發送一個POST請求
axios.post('/user',{ firstName:'Fred', lastName:'Flintstone' }) .then(function(res){ console.log(res); }) .catch(function(err){ console.log(err); });
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){ //當這兩個請求都完成的時候會觸發這個函數,兩個參數分別代表返回的結果 }))
三、axios的API
(一) axios可以通過配置(config)來發送請求(qiu)
1、 axios(config)
//發送一個`POST`請求 axios({ method:"POST", url:'/user/12345', data:{ firstName:"Fred", lastName:"Flintstone" } });
2、 axios(url[,config])
//發送一個`GET`請求(默認的請求方式) axios('/user/12345');
(二(er))、 請求(qiu)方式的別(bie)名(ming),這(zhe)里對所有已經(jing)支持的請求(qiu)方式都(dou)提供了方便的別(bie)名(ming)
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]])
注意:當我們在(zai)使(shi)用別名(ming)方法的(de)時候(hou),url,method,data這幾個參數不需要在(zai)配(pei)置中聲明(ming)
(三(san))、 并發請(qing)求(concurrency),即(ji)是(shi)幫助(zhu)處理并發請(qing)求的輔助(zhu)函數(shu)
//iterable是一個可以迭代的參數如數組等 axios.all(iterable) //callback要等到所有請求都完成才會執行 axios.spread(callback)
(四)、創建一個(ge)axios實例,并且可以(yi)自定義其配置(zhi)
1、 axios.create([config])
var instance = axios.create({ baseURL:"//some-domain.com/api/", timeout:1000, headers: {'X-Custom-Header':'foobar'} });
2、 實例的方法
一(yi)下是實例方法(fa),注(zhu)意已經(jing)定義的配(pei)(pei)置將和利用create創建的實例的配(pei)(pei)置合(he)并(bing)
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 config)
以下就是(shi)請求的(de)(de)配置(zhi)選(xuan)項,只(zhi)有url選(xuan)項是(shi)必(bi)須的(de)(de),如果method選(xuan)項未定義,那么它默認是(shi)以GET的(de)(de)方(fang)式發出請求
{ //`url`是請求的服務器地址 url:'/user', //`method`是請求資源的方式 method:'get'//default //如果`url`不是絕對地址,那么`baseURL`將會加到`url`的前面 //當`url`是相對地址的時候,設置`baseURL`會非常的方便 baseURL:'//some-domain.com/api/', //`transformRequest`選項允許我們在請求發送到服務器之前對請求的數據做出一些改動 //該選項只適用于以下請求方式:`put/post/patch` //數組里面的最后一個函數必須返回一個字符串、-一個`ArrayBuffer`或者`Stream` transformRequest:[function(data){ //在這里根據自己的需求改變數據 return data; }], //`transformResponse`選項允許我們在數據傳送到`then/catch`方法之前對數據進行改動 transformResponse:[function(data){ //在這里根據自己的需求改變數據 return data; }], //`headers`選項是需要被發送的自定義請求頭信息 headers: {'X-Requested-With':'XMLHttpRequest'}, //`params`選項是要隨請求一起發送的請求參數----一般鏈接在URL后面 //他的類型必須是一個純對象或者是URLSearchParams對象 params: { ID:12345 }, //`paramsSerializer`是一個可選的函數,起作用是讓參數(params)序列化 //例如(//www.npmjs.com/package/qs,//api.jquery.com/jquery.param) paramsSerializer: function(params){ return Qs.stringify(params,{arrayFormat:'brackets'}) }, //`data`選項是作為一個請求體而需要被發送的數據 //該選項只適用于方法:`put/post/patch` //當沒有設置`transformRequest`選項時dada必須是以下幾種類型之一 //string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams //僅僅瀏覽器:FormData/File/Bold //僅node:Stream data { firstName:"Fred" }, //`timeout`選項定義了請求發出的延遲毫秒數 //如果請求花費的時間超過延遲的時間,那么請求會被終止 timeout:1000, //`withCredentails`選項表明了是否是跨域請求 withCredentials:false,//default //`adapter`適配器選項允許自定義處理請求,這會使得測試變得方便 //返回一個promise,并提供驗證返回 adapter: function(config){ /*..........*/ }, //`auth`表明HTTP基礎的認證應該被使用,并提供證書 //這會設置一個authorization頭(header),并覆蓋你在header設置的Authorization頭信息 auth: { username:"zhangsan", password: "s00sdkf" }, //返回數據的格式 //其可選項是arraybuffer,blob,document,json,text,stream responseType:'json',//default // xsrfCookieName: 'XSRF-TOKEN',//default xsrfHeaderName:'X-XSRF-TOKEN',//default //`onUploadProgress`上傳進度事件 onUploadProgress:function(progressEvent){ //下載進度的事件 onDownloadProgress:function(progressEvent){ } }, //相應內容的最大值 maxContentLength:2000, //`validateStatus`定義了是否根據http相應狀態碼,來resolve或者reject promise //如果`validateStatus`返回true(或者設置為`null`或者`undefined`),那么promise的狀態將會是resolved,否則其狀態就是rejected validateStatus:function(status){ return status >= 200 && status <300;//default }, //`maxRedirects`定義了在nodejs中重定向的最大數量 maxRedirects: 5,//default //`httpAgent/httpsAgent`定義了當發送http/https請求要用到的自定義代理 //keeyAlive在選項中沒有被默認激活 httpAgent: new http.Agent({keeyAlive:true}), httpsAgent: new https.Agent({keeyAlive:true}), //proxy定義了主機名字和端口號, //`auth`表明http基本認證應該與proxy代理鏈接,并提供證書 //這將會設置一個`Proxy-Authorization` header,并且會覆蓋掉已經存在的`Proxy-Authorization` header proxy: { host:'127.0.0.1', port: 9000, auth: { username:'skda', password:'radsd' } }, //`cancelToken`定義了一個用于取消請求的cancel token //詳見cancelation部分 cancelToken: new cancelToken(function(cancel){ }) }
五、請求返回的內容
{ data:{}, status:200, //從服務器返回的http狀態文本 statusText:'OK', //響應頭信息 headers: {}, //`config`是在請求的時候的一些配置信息 config: {} }
你(ni)可以這樣來獲(huo)取響應(ying)信(xin)息
axios.get('/user/12345') .then(function(res){ console.log(res.data); console.log(res.status); console.log(res.statusText); console.log(res.headers); console.log(res.config); })
六、默認配置
你可以設置(zhi)默認(ren)配(pei)置(zhi),對所有(you)請求都有(you)效(xiao)
1、 全局默認配置
axios.defaults.baseURL = '//api.exmple.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
2、 自定義的實例默(mo)認設置
//當創建實例的時候配置默認配置 var instance = axios.create({ baseURL: '//api.example.com' }); //當實例創建時候修改配置 instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
3、 配置中(zhong)的有優先級(ji)
config配(pei)置將會以(yi)優(you)先級別來合并(bing),順序是(shi)(shi)lib/defauts.js中的默認配(pei)置,然后(hou)是(shi)(shi)實例中的默認配(pei)置,最后(hou)是(shi)(shi)請求中的config參數的配(pei)置,越往后(hou)等級越高,后(hou)面(mian)的會覆蓋前(qian)面(mian)的例子。
//創建一個實例的時候會使用libray目錄中的默認配置 //在這里timeout配置的值為0,來自于libray的默認值 var instance = axios.create(); //回覆蓋掉library的默認值 //現在所有的請求都要等2.5S之后才會發出 instance.defaults.timeout = 2500; //這里的timeout回覆蓋之前的2.5S變成5s instance.get('/longRequest',{ timeout: 5000 });
七、攔截器
你可以在請求、響(xiang)應在到達then/catch之前攔截他(ta)們
//添加一個(ge)請求攔截(jie)器
axios.interceptors.request.use(function(config){
//在請求發出之前進行一些操作
return config;
},function(err){
//Do something with request error
return Promise.reject(error);
});
//添加(jia)一個響應攔截器
axios.interceptors.response.use(function(res){
//在這(zhe)里對返回的數據進行處理
return res;
},function(err){
//Do something with response error
return Promise.reject(error);
})
2、取消攔截器
var myInterceptor = axios.interceptor.request.use(function(){/*....*/}); axios.interceptors.request.eject(myInterceptor);
3、 給自定義的(de)axios實例添(tian)加(jia)攔截器(qi)
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.header); }else { //一些錯誤是在設置請求的時候觸發 console.log('Error',error.message); } console.log(error.config); });
九、取消
你(ni)可以通過(guo)一個cancel token來取消(xiao)一個請求
你可以通過CancelToken.source工廠函數來創建一個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 } }); //取消請求(信息的參數可以設置的) source.cance("操作被用戶取消");
你可以給cancelToken構造函數傳(chuan)遞一個executor function來創建一個cancel token:
var cancelToken = axios.CancelToken; var cance; axios.get('/user/12345',{ cancelToken: new CancelToken(function(c){ //這個executor函數接受一個cancel function作為參數 cancel = c; }) }) //取消請求 cancel();