axios中文說明Axios是一個基于promise的HTTP庫可以用在瀏覽器_第1頁
axios中文說明Axios是一個基于promise的HTTP庫可以用在瀏覽器_第2頁
axios中文說明Axios是一個基于promise的HTTP庫可以用在瀏覽器_第3頁
axios中文說明Axios是一個基于promise的HTTP庫可以用在瀏覽器_第4頁
axios中文說明Axios是一個基于promise的HTTP庫可以用在瀏覽器_第5頁
已閱讀5頁,還剩10頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領

文檔簡介

AxiospromiseHTTPnode.jsnode.jshttp支持PromiseAPI自動轉(zhuǎn)換JSON數(shù)據(jù)LatestLatestLatestLatestLatestLatest8+$$npminstall使用$$bowerinstall<script<script執(zhí) 請為給定ID的user.then(function{.catch(function{{params:{ID:}.then(function{.catch(function{執(zhí) 請{firstName:'Fred',lastName:'Flintstone'.then(function{.catch(function{functionfunction{return}functiongetUserPermissions()return}.then(axios.spread(function(acct,perms)axios 發(fā)送發(fā)送POST請求method:'post',data:{firstName:'Fred',lastName:'Flintstone'}axios(url[,發(fā)送GET請求(默認的方法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]]) 并創(chuàng)建實

varvarinstance=axios.create({baseURL:'httpstimeout:headers:{'X-Custom-Header':實例方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]])

{`url`是用于請求的服務器URLurl:'/user',`method`methodget'默認是//`baseURL`將自動加在`url`前面,除非`url`是一個絕對URL//它可以通過設置一個`baseURL`便于為axios實例的方法傳遞相對URLbaseURL:'https 只能用在'PUT'POST和'PATCH//后面數(shù)組中的函數(shù)必須返回一個字符串,或ArrayBuffer,或StreamtransformRequest:[function(data){對datareturn`transformResponse`在傳遞給then/catchtransformResponse:[function(data)對datareturn`headers`headers:{'X-Requested-With'://`params`是即將與請求一起發(fā)送的URL//必須是一個無格式對象 inobject)或URLSearchParams對{ID:`paramsSerializer`是一個負責`params`//(e.g. /package/qs, paramsSerializer:function(params)returnQs.stringify(params,{arrayFormat:`data`//只適用于這些請求方法'PUT'POST',和在沒有設置`transformRequest`//- inobject,ArrayBuffer,ArrayBufferView,//-瀏覽器專 FormData,File,//-Node專屬 data:{firstName:`timeout`指定請求超時的毫秒數(shù)(0表示無超時時間//如果請求話費了超過`timeout`timeout:withCredentials:false`adapter`返回一個promise并應用一個有效的響應(查閱[responsedocs](#response-api)).adapter:function(config){/*...//`auth`表示應該使用HTTP//這將設置一個`Authorization`頭,覆寫掉現(xiàn)有的任意使用`headers`設置的自定義`Authorizatioauth:username:'janedoe',password:'s00pers3cret'//`responseType`表示服務器響應的數(shù)據(jù)類型,可以是'arraybuffer','blob',' ','json','text','stream'responseType:'json// Name`是用作xsrftoken的值 Name:'XSRF-TOKEN',//`xsrfHeaderName`是承載xsrftoken的值的HTTPxsrfHeaderName:'X-XSRF-TOKEN'`onUploadProgress`onUploadProgress:function(progressEvent)//對原生進 //`onDownloadProgress`允許 onDownloadProgress:function(progressEvent)//對原生進 //`validateStatus`定義對于給定的HTTP響應狀態(tài)碼是resolve或rejectpromise。如果`validateStatus`返回`true`(或者設置為`null`或`undefined`),promise將被resolve;否則,promise將被rejectevalidateStatus:function(status)returnstatus200&&status300`maxRedirects`定義在node.js中follow如果設置為0,將不會followmaxRedirects:5,`httpAgent`和`httpsAgent`分別在node.js中用于定義在執(zhí)行http和https`keepAlive`httpAgent:newhttp.Agent({keepAlive:truehttpsAgent:newhttps.Agent({keepAlive:true// '定 //`auth`表示HTTP基礎驗證應當用于連 //這將會設置一個 -Authorization`頭,覆寫掉已有的通過使用`header`設置的自定義:host:auth::{username:'mikeymike',password:'rapunz3l'}`cancelToken`指定用于取消請求的cancel//(查看后面的Cancellation這節(jié)了 cancelToken:newCancelToken(function(cancel)}{{`data`data://`status`來自服務器響應的HTTPstatus:`statusText`來自服務器響應的HTTPstatusText:`headers`headers:`config`config:}使 {console.log(response.data); 時,或傳遞rejectioncallback作為 配置的默認值axios //此時超時配置的默認值是varinstance=//現(xiàn)在,在超時前,所有請求都會等待2.5instance.defaults.timeout={timeout:器 ////添加請 return},function(error)return//添加響 return},function(error)returnvarvarmyInterceptor=erceptors.request.use(function(){/*...*/});可以為自定義axios實例添加varinstance=axios.create();erceptors.request.use(functionvarinstance=axios.create();erceptors.request.use(function(){/*...*/}); 配置選項定義一個自定義HTTP狀態(tài)碼的錯誤范圍{validateStatus:function(status)returnstatus500狀態(tài)碼在大于或等于500時才會}canceltokenvarCancelToken=axios.CancelToken;varsource=CancelToken.source();{cancelToken:}).catch(function(thrown){if(axios.isCancel(thrown)){console.log('Requestcanceled',}else}取消請求(message參數(shù)是可選的source.cancel('OperationvarCancelToken=axios.CancelToken;varsource=CancelToken.source();{cancelToken:}).catch(function(thrown){if(axios.isCancel(thrown)){console.log('Requestcanceled',}else}取消請求(message參數(shù)是可選的source.cancel('Operationcanceledbythe還可以通過傳遞一個executor函數(shù) 的構(gòu)造函數(shù)來創(chuàng)建cancelvarvarCancelToken=axios.CancelToken;varcancel;cancelToken:newCancelToken(functionexecutor(c)executor函數(shù)接收一個cancelcancel=NotecanceltokenUntilaxiosreaches release,breakingchangeswillbereleasedwithanewminorversion.

, willhavethesameAPI, willhavebreakingaxiosES6PromiseES6Promiseimportaxiosfrom'axios';importaxiosfrom'axios';UpgradeGuideCodeofConductaxiosisheavilyinspiredbythe$httpserviceprovidedinAngular. yaxiosisanefforttoprovide

-likeserviceforuseoutsideofUpgrade0.13.x->TheaxiosTypeScriptdefinitionshavebeenupdatedtomatchtheaxiosAPIandusetheES2015modulePleaseusethe statementtoimportaxiosinimportimportaxiosfrom'axios';.then(response=>.catch(error=>

Configconfigoptionhasbeen cedwithtwonew Pleaseusethem{{//DefineacustomagentforhttpAgent:newhttp.Agent({keepAlive:true//DefineacustomagentforhttpsAgent:newhttps.Agent({keepAlive:true}

Configconfigoptionhasbeenrecedwiththe

{{//DefineahandlerforuploadprogresseventsonUploadProgress:function(progressEvent){////DefineahandlerfordownloadprogresseventsonDownloadProgress:function(progressEvent){//}}0.12.x-> releasecontainsseveralchangestocustomadaptersanderrorErrorPrevioustothisreleaseanerrorcouldeitherbeaserverresponsewithbadstatuscodeoran.WiththisreleasePromisewillalwaysrejectwithan .Inthecasethataresponsewasreceived,the willalsoincludetheresponse..catch((error){console.log(error.message);console.log(error.code);//Notalwaysspecifiedconsole.log(error.config);//Theconfigthatwasusedtomaketherequestconsole.log(error.response);//OnlyavailableifresponsewasreceivedfromtheseRequestThisreleasechangesafewthingsabouthowrequestadapterswork.Pleasetakenoteifyouareusingyourowncustomadapter.ResponsetransformerisnowcalledoutsideofRequestadapterreturns Thismeansthatyounolongerneedto onresponsedata.YouwillalsolongerreceivePrevious

asargumentsinyourfunctionfunctionmyAdapter(resolve,reject,{varresponse={transformData(responseData,responseHeaders,status:request.status,statusText:request.statusText,headers:responseHeaderssettle(resolve,reject,}NewfunctionfunctionmyAdapter(config)returnnewPromise(function(resolve,{varresponse={data:responseData,status:request.status,statusText:request.statusText,headers:responseHeaderssettle(resolve,reject,}Seetherelatedcommitsformoredetails:Responsetransformers0.5.x->

releasecontainsmostlybugfixes,butthereareacouplethingstobeawareofES6PromiseUpuntilthe releaseES6 wasbeingpolyfilledusinges6-promise.Withthisrelease,thepolyfillhasbeenremoved,andyouwillneedtosupplyityourselfifyourenvironmentneedsit.varaxios=require('axios');Thiswillpolyfilltheglobalenvironment,andonlyneedstobedone/

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論