asiox

axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

功能特性

在浏览器中发送XMLHttpRequests请求

在 node.js 中发送http请求

支持Promise API

拦截请求和响应

转换请求和响应数据

自动转换 JSON 数据

客户端支持保护安全免受XSRF攻击

浏览器支持


安装

使用 bower:

$ bowerinstallaxios

使用 npm:

$ npminstallaxios

例子

发送一个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);});

发送一个POST请求

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

发送多个并发请求

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传递对应的参数来定制请求:

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

请求方法别名

为方便起见,我们为所有支持的请求方法都提供了别名

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、method和data属性不需要在 config 参数里面指定。

并发

处理并发请求的帮助方法

axios.all(iterable)

axios.spread(callback)

创建一个实例

你可以用自定义配置创建一个新的 axios 实例。

axios.create([config])

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

实例方法

所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。

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

请求配置

下面是可用的请求配置项,只有url是必需的。如果没有指定method,默认的请求方法是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}}

响应的数据结构

响应的数据包括下面的信息:

{// `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:{}}

当使用then或者catch时, 你会收到下面的响应:

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

默认配置

你可以为每一个请求指定默认配置。

全局 axios 默认配置

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

自定义实例默认配置

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

配置的优先顺序

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之前拦截请求和响应

// 添加一个请求拦截器axios.interceptors.request.use(function(config){// Do something before request is sentreturnconfig;},function(error){// Do something with request errorreturnPromise.reject(error);});// 添加一个响应拦截器axios.interceptors.response.use(function(response){// Do something with response datareturnresponse;},function(error){// Do something with response errorreturnPromise.reject(error);});

移除一个拦截器:

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

你可以给一个自定义的 axios 实例添加拦截器:

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

错误处理

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 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入polyfill

TypeScript

axios 包含一个TypeScript定义

///

import * as axios from 'axios';

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,580评论 18 139
  • =========================================================...
    lavor阅读 3,482评论 0 5
  • “思凯比尔,你知道红月和金月的故事吗?”一个苍老的声音说道。 “不,圣者,我们从来没有时间关心那个,相比之下,我对...
    道天生阅读 379评论 0 1
  • 傍晚6,7点样子,和什么人一起去过河,好像是自己的孩子也好像是自己的弟弟,这两个人在梦里老是混淆的。不清楚原因,怀...
    梦里疯阅读 195评论 0 0