asiox

axios

基于 Promise 的 HTTP 請(qǐng)求客戶(hù)端普筹,可同時(shí)在瀏覽器和 node.js 中使用

功能特性

在瀏覽器中發(fā)送XMLHttpRequests請(qǐng)求

在 node.js 中發(fā)送http請(qǐng)求

支持Promise?API

攔截請(qǐng)求和響應(yīng)

轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)

自動(dòng)轉(zhuǎn)換 JSON 數(shù)據(jù)

客戶(hù)端支持保護(hù)安全免受XSRF攻擊

瀏覽器支持


安裝

使用 bower:

$ bowerinstallaxios

使用 npm:

$ npminstallaxios

例子

發(fā)送一個(gè)GET請(qǐng)求

// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(response){console.log(response);});// Optionally the request above could also be done asaxios.get('/user',{params:{ID:12345}}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});

發(fā)送一個(gè)POST請(qǐng)求

axios.post('/user',{firstName:'Fred',lastName:'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});

發(fā)送多個(gè)并發(fā)請(qǐng)求

functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){// Both requests are now complete}));

axios API

可以通過(guò)給axios傳遞對(duì)應(yīng)的參數(shù)來(lái)定制請(qǐng)求:

axios(config)

// Send a POST requestaxios({method:'post',url:'/user/12345',data:{firstName:'Fred',lastName:'Flintstone'}});

axios(url[, config])

// Sned a GET request (default method)axios('/user/12345');

請(qǐng)求方法別名

為方便起見(jiàn)如庭,我們?yōu)樗兄С值恼?qǐng)求方法都提供了別名

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]])

注意

當(dāng)使用別名方法時(shí)剂娄,url、method和data屬性不需要在 config 參數(shù)里面指定。

并發(fā)

處理并發(fā)請(qǐng)求的幫助方法

axios.all(iterable)

axios.spread(callback)

創(chuàng)建一個(gè)實(shí)例

你可以用自定義配置創(chuàng)建一個(gè)新的 axios 實(shí)例。

axios.create([config])

varinstance=axios.create({baseURL:'https://some-domain.com/api/',timeout:1000,headers:{'X-Custom-Header':'foobar'}});

實(shí)例方法

所有可用的實(shí)例方法都列在下面了,指定的配置將會(huì)和該實(shí)例的配置合并说铃。

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]])

請(qǐng)求配置

下面是可用的請(qǐng)求配置項(xiàng),只有url是必需的嘹履。如果沒(méi)有指定method腻扇,默認(rèn)的請(qǐng)求方法是GET。

{// `url` is the server URL that will be used for the requesturl:'/user',// `method` is the request method to be used when making the requestmethod:'get',// default// `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance.baseURL:'https://some-domain.com/api/',// `transformRequest` allows changes to the request data before it is sent to the server// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'// The last function in the array must return a string or an ArrayBuffertransformRequest:[function(data){// Do whatever you want to transform the datareturndata;}],// `transformResponse` allows changes to the response data to be made before// it is passed to then/catchtransformResponse:[function(data){// Do whatever you want to transform the datareturndata;}],// `headers` are custom headers to be sentheaders:{'X-Requested-With':'XMLHttpRequest'},// `params` are the URL parameters to be sent with the requestparams:{ID:12345},// `paramsSerializer` is an optional function in charge of serializing `params`// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer:function(params){returnQs.stringify(params,{arrayFormat:'brackets'})},// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', and 'PATCH'// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hashdata:{firstName:'Fred'},// `timeout` specifies the number of milliseconds before the request times out.// If the request takes longer than `timeout`, the request will be aborted.timeout:1000,// `withCredentials` indicates whether or not cross-site Access-Control requests// should be made using credentialswithCredentials:false,// default// `adapter` allows custom handling of requests which makes testing easier.// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).adapter:function(resolve,reject,config){/* ... */},// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.// This will set an `Authorization` header, overwriting any existing// `Authorization` custom headers you have set using `headers`.auth:{username:'janedoe',password:'s00pers3cret'}// `responseType` indicates the type of data that the server will respond with// options are 'arraybuffer', 'blob', 'document', 'json', 'text'responseType:'json',// default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName:'XSRF-TOKEN',// default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName:'X-XSRF-TOKEN',// default// `progress` allows handling of progress events for 'POST' and 'PUT uploads'// as well as 'GET' downloadsprogress:function(progressEvent){// Do whatever you want with the native progress event}}

響應(yīng)的數(shù)據(jù)結(jié)構(gòu)

響應(yīng)的數(shù)據(jù)包括下面的信息:

{// `data` is the response that was provided by the serverdata:{},// `status` is the HTTP status code from the server responsestatus:200,// `statusText` is the HTTP status message from the server responsestatusText:'OK',// `headers` the headers that the server responded withheaders:{},// `config` is the config that was provided to `axios` for the requestconfig:{}}

當(dāng)使用then或者catch時(shí), 你會(huì)收到下面的響應(yīng):

axios.get('/user/12345').then(function(response){console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});

默認(rèn)配置

你可以為每一個(gè)請(qǐng)求指定默認(rèn)配置砾嫉。

全局 axios 默認(rèn)配置

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';

自定義實(shí)例默認(rèn)配置

// Set config defaults when creating the instancevarinstance=axios.create({baseURL:'https://api.example.com'});// Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization']=AUTH_TOKEN;

配置的優(yōu)先順序

Config will be merged with an order of precedence. The order is library defaults found inlib/defaults.js, thendefaultsproperty of the instance, and finallyconfigargument for the request. The latter will take precedence over the former. Here's an example.

// Create an instance using the config defaults provided by the library// At this point the timeout config value is `0` as is the default for the libraryvarinstance=axios.create();// Override timeout default for the library// Now all requests will wait 2.5 seconds before timing outinstance.defaults.timeout=2500;// Override timeout for this request as it's known to take a long timeinstance.get('/longRequest',{timeout:5000});

攔截器

你可以在處理then或catch之前攔截請(qǐng)求和響應(yīng)

// 添加一個(gè)請(qǐng)求攔截器axios.interceptors.request.use(function(config){// Do something before request is sentreturnconfig;},function(error){// Do something with request errorreturnPromise.reject(error);});// 添加一個(gè)響應(yīng)攔截器axios.interceptors.response.use(function(response){// Do something with response datareturnresponse;},function(error){// Do something with response errorreturnPromise.reject(error);});

移除一個(gè)攔截器:

varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);

你可以給一個(gè)自定義的 axios 實(shí)例添加攔截器:

varinstance=axios.create();instance.interceptors.request.use(function(){/*...*/});

錯(cuò)誤處理

axios.get('/user/12345').catch(function(response){if(responseinstanceofError){// Something happened in setting up the request that triggered an Errorconsole.log('Error',response.message);}else{// The request was made, but the server responded with a status code// that falls out of the range of 2xxconsole.log(response.data);console.log(response.status);console.log(response.headers);console.log(response.config);}});

Promises

axios 依賴(lài)一個(gè)原生的 ES6 Promise 實(shí)現(xiàn)幼苛,如果你的瀏覽器環(huán)境不支持 ES6 Promises,你需要引入polyfill

TypeScript

axios 包含一個(gè)TypeScript定義

///

import * as axios from 'axios';

axios.get('/user?ID=12345');

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末焕刮,一起剝皮案震驚了整個(gè)濱河市舶沿,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌配并,老刑警劉巖括荡,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異溉旋,居然都是意外死亡畸冲,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門(mén)低滩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)召夹,“玉大人岩喷,你說(shuō)我怎么就攤上這事恕沫。” “怎么了纱意?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵婶溯,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng)迄委,這世上最難降的妖魔是什么褐筛? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮叙身,結(jié)果婚禮上渔扎,老公的妹妹穿的比我還像新娘。我一直安慰自己信轿,他們只是感情好晃痴,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著财忽,像睡著了一般倘核。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上即彪,一...
    開(kāi)封第一講書(shū)人閱讀 52,156評(píng)論 1 308
  • 那天紧唱,我揣著相機(jī)與錄音,去河邊找鬼隶校。 笑死漏益,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的深胳。 我是一名探鬼主播遭庶,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼稠屠!你這毒婦竟也來(lái)了峦睡?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤权埠,失蹤者是張志新(化名)和其女友劉穎榨了,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體攘蔽,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡龙屉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了满俗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片转捕。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖唆垃,靈堂內(nèi)的尸體忽然破棺而出五芝,到底是詐尸還是另有隱情,我是刑警寧澤辕万,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布枢步,位于F島的核電站沉删,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏醉途。R本人自食惡果不足惜矾瑰,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望隘擎。 院中可真熱鬧殴穴,春花似錦、人聲如沸货葬。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)宝惰。三九已至植榕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間尼夺,已是汗流浹背尊残。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留淤堵,地道東北人寝衫。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像拐邪,于是被迫代替她去往敵國(guó)和親慰毅。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理扎阶,服務(wù)發(fā)現(xiàn)汹胃,斷路器,智...
    卡卡羅2017閱讀 134,693評(píng)論 18 139
  • =========================================================...
    lavor閱讀 3,492評(píng)論 0 5
  • “思凱比爾东臀,你知道紅月和金月的故事嗎着饥?”一個(gè)蒼老的聲音說(shuō)道。 “不惰赋,圣者宰掉,我們從來(lái)沒(méi)有時(shí)間關(guān)心那個(gè),相比之下赁濒,我對(duì)...
    道天生閱讀 385評(píng)論 0 1
  • 傍晚6,7點(diǎn)樣子轨奄,和什么人一起去過(guò)河,好像是自己的孩子也好像是自己的弟弟拒炎,這兩個(gè)人在夢(mèng)里老是混淆的挪拟。不清楚原因,懷...
    夢(mèng)里瘋閱讀 202評(píng)論 0 0