asiox

axios

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

功能特性

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

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

支持Promise?API

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

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

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

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

瀏覽器支持


安裝

使用 bower:

$ bowerinstallaxios

使用 npm:

$ npminstallaxios

例子

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

// 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請求

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

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

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

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

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

請求方法別名

為方便起見,我們?yōu)樗兄С值恼埱蠓椒ǘ继峁┝藙e名

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ā)請求的幫助方法

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

請求配置

下面是可用的請求配置項(xiàng),只有url是必需的。如果沒有指定method,默認(rèn)的請求方法是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è)請求指定默認(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之前攔截請求和響應(yīng)

// 添加一個(gè)請求攔截器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 依賴一個(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)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • =========================================================...
    lavor閱讀 3,656評(píng)論 0 5
  • “思凱比爾,你知道紅月和金月的故事嗎?”一個(gè)蒼老的聲音說道。 “不,圣者,我們從來沒有時(shí)間關(guān)心那個(gè),相比之下,我對(duì)...
    道天生閱讀 474評(píng)論 0 1
  • 傍晚6,7點(diǎn)樣子,和什么人一起去過河,好像是自己的孩子也好像是自己的弟弟,這兩個(gè)人在夢里老是混淆的。不清楚原因,懷...
    夢里瘋閱讀 255評(píng)論 0 0

友情鏈接更多精彩內(nèi)容