axios中文文档

axios

基于promise用于浏览器和node.js的http客户端

特点

支持浏览器和node.js

支持promise

能拦截请求和响应

能转换请求和响应数据

能取消请求

自动转换JSON数据

浏览器端支持防止CSRF(跨站请求伪造)

安装

npm安装

$ npm install axios

bower安装

$ bower install axios

通过cdn引入

例子

发起一个GET请求

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

发起一个POST请求

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

同时发起多个请求

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(config)

// 发起一个POST请求axios({  method:'post',  url:'/user/12345',  data: {    firstName:'Fred',    lastName:'Flintstone'}});

// 获取远程图片axios({method:'get',url:'http://bit.ly/2mTM3nY',responseType:'stream'})  .then(function(response){  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});

axios(url[, config])

// 发起一个GET请求(GET是默认的请求方法)axios('/user/12345');

请求方法别名

为了方便我们为所有支持的请求方法均提供了别名。

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(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.creat([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#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

请求配置

下面是所有可用的请求配置项,只有url是必填,默认的请求方法是GET,如果没有指定请求方法的话。

{// `url` 是请求的接口地址url:'/user',// `method` 是请求的方法method:'get',// 默认值// 如果url不是绝对路径,那么会将baseURL和url拼接作为请求的接口地址// 用来区分不同环境,建议使用baseURL:'https://some-domain.com/api/',// 用于请求之前对请求数据进行操作// 只用当请求方法为‘PUT’,‘POST’和‘PATCH’时可用// 最后一个函数需return出相应数据// 可以修改headerstransformRequest: [function(data, headers){// 可以对data做任何操作returndata;  }],// 用于对相应数据进行处理// 它会通过then或者catchtransformResponse: [function(data){// 可以对data做任何操作returndata;  }],// `headers` are custom headers to be sentheaders: {'X-Requested-With':'XMLHttpRequest'},// URL参数// 必须是一个纯对象或者 URL参数对象params: {ID:12345},// 是一个可选的函数负责序列化`params`// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer:function(params){returnQs.stringify(params, {arrayFormat:'brackets'})  },// 请求体数据// 只有当请求方法为'PUT', 'POST',和'PATCH'时可用// 当没有设置`transformRequest`时,必须是以下几种格式// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - Browser only: FormData, File, Blob// - Node only: Stream, Bufferdata: {firstName:'Fred'},// 请求超时时间(毫秒)timeout:1000,// 是否携带cookie信息withCredentials:false,// default// 统一处理request让测试更加容易// 返回一个promise并提供一个可用的response// 其实我并不知道这个是干嘛的!!!!// (see lib/adapters/README.md).adapter:function(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'},// 响应格式// 可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'responseType:'json',// 默认值是json// `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// 处理上传进度事件onUploadProgress:function(progressEvent){// Do whatever you want with the native progress event},// 处理下载进度事件onDownloadProgress:function(progressEvent){// Do whatever you want with the native progress event},// 设置http响应内容的最大长度maxContentLength:2000,// 定义可获得的http响应状态码// return true、设置为null或者undefined,promise将resolved,否则将rejectedvalidateStatus:function(status){returnstatus >=200&& status <300;// default},// `maxRedirects` defines the maximum number of redirects to follow in node.js.// If set to 0, no redirects will be followed.// 最大重定向次数?没用过不清楚maxRedirects:5,// default// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http// and https requests, respectively, in node.js. This allows options to be added like// `keepAlive` that are not enabled by default.httpAgent:newhttp.Agent({keepAlive:true}),httpsAgent:newhttps.Agent({keepAlive:true}),// 'proxy' defines the hostname and port of the proxy server// Use `false` to disable proxies, ignoring environment variables.// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and// supplies credentials.// This will set an `Proxy-Authorization` header, overwriting any existing// `Proxy-Authorization` custom headers you have set using `headers`.// 代理proxy: {host:'127.0.0.1',port:9000,auth: {username:'mikeymike',password:'rapunz3l'}  },// `cancelToken` specifies a cancel token that can be used to cancel the request// (see Cancellation section below for details)// 用于取消请求?又是一个不知道怎么用的配置项cancelToken:newCancelToken(function(cancel){  })}

响应组成

response由以下几部分信息组成

{// 服务端返回的数据data: {},// 服务端返回的状态码status:200,// 服务端返回的状态信息statusText:'OK',// 响应头// 所有的响应头名称都是小写headers: {},// axios请求配置config: {},// 请求request: {}}

用then接收以下响应信息

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

实例默认配置

// 创建实例时修改配置varinstance = axios.create({baseURL:'https://api.example.com'});// 实例创建之后修改配置instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置优先级

配置项通过一定的规则合并,request config>instance.defaults>系统默认,优先级高的覆盖优先级低的。

// 创建一个实例,这时的超时时间为系统默认的 0varinstance = axios.create();// 通过instance.defaults重新设置超时时间为2.5s,因为优先级比系统默认高instance.defaults.timeout =2500;// 通过request config重新设置超时时间为5s,因为优先级比instance.defaults和系统默认都高instance.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(error){if(error.response) {// 发送请求后,服务端返回的响应码不是 2xx  console.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);    }elseif(error.request) {// 发送请求但是没有响应返回console.log(error.request);    }else{// 其他错误console.log('Error', error.message);    }console.log(error.config);  });

你可以用validateStatus定义一个http状态码返回的范围.

axios.get('/user/12345', {validateStatus:function(status){returnstatus <500;// Reject only if the status code is greater than or equal to 500}})

取消请求

你可以通过cancel token来取消一个请求

The axios cancel token API is based on the withdrawncancelable promises proposal.

You can create a cancel token using theCancelToken.sourcefactory as shown below:

varCancelToken = axios.CancelToken;varsource = 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}});// cancel the request (the message parameter is optional)source.cancel('Operation canceled by the user.');

You can also create a cancel token by passing an executor function to theCancelTokenconstructor:

varCancelToken = axios.CancelToken;varcancel;axios.get('/user/12345', {cancelToken:newCancelToken(functionexecutor(c){// An executor function receives a cancel function as a parametercancel = c;  })});// cancel the requestcancel();

Note: you can cancel several requests with the same cancel token.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects toJSON. To send data in theapplication/x-www-form-urlencodedformat instead, you can use one of the following options.

Browser

In a browser, you can use theURLSearchParamsAPI as follows:

varparams =newURLSearchParams();params.append('param1','value1');params.append('param2','value2');axios.post('/foo', params);

Note thatURLSearchParamsis not supported by all browsers (seecaniuse.com), but there is apolyfillavailable (make sure to polyfill the global environment).

Alternatively, you can encode data using theqslibrary:

varqs =require('qs');axios.post('/foo', qs.stringify({'bar':123}));

Node.js

In node.js, you can use thequerystringmodule as follows:

varquerystring =require('querystring');axios.post('http://something.com/', querystring.stringify({foo:'bar'}));

You can also use theqslibrary.

Semver

Until axios reaches a1.0release, breaking changes will be released with a new minor version. For example0.5.1, and0.5.4will have the same API, but0.6.0will have breaking changes.

Promises

axios depends on a native ES6 Promise implementation to besupported.

If your environment doesn't support ES6 Promises, you canpolyfill.

TypeScript

axios includesTypeScriptdefinitions.

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

Resources

Changelog

Upgrade Guide

Ecosystem

Contributing Guide

Code of Conduct

Credits

axios is heavily inspired by the$http serviceprovided inAngular. Ultimately axios is an effort to provide a standalone$http-like service for use outside of Angular.

License

MIT

作者:Lewis19990

链接:https://www.jianshu.com/p/7a9fbcbb1114

來源:简书

简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

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

推荐阅读更多精彩内容

  • axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在...
    Yanghc阅读 3,583评论 0 7
  • Vue.js 1.0 我们常使用 vue-resource (官方ajax库), Vue 2.0 发布后作者宣告不...
    九四年的风阅读 23,787评论 1 8
  • 生活把菱角给磨圆润,想想出来工作之后把自己的一些坏脾气收敛了许多,可能这也是一种适应生活的态度吧。说到适应我之前一...
    咸鱼丁阅读 1,566评论 5 3
  • 今早看到微博上爆出至上励合成员刘洲成家暴妻子的消息,不禁一阵唏嘘,怎么会有这样的男人? 连孕期和月子里都不放过,居...
    e035443af3e2阅读 353评论 0 1
  • (5年前刚毕业经历挫折后写的,不押韵,欢迎重新改写!) 候鸟离枝直向北, 突经大漠风暴起; 方知风沙胜微风, 无力...
    来自地狱_再入地狱怕吗阅读 202评论 0 0