这次给大家带来axios怎样基于promise的http请求客户端,axios基于promise的http请求客户端的注意事项有哪些,下面就是实战案例,一起来看一下。
axios
基于 promise 的 http 请求客户端,可同时在浏览器和 node.js 中使用
功能特性
在浏览器中发送xmlhttprequests请求
在 node.js 中发送http请求
支持promiseapi
拦截请求和响应
转换请求和响应数据
自动转换 json 数据
客户端支持保护安全免受xsrf攻击
浏览器支持
安装
使用 bower:
$ bower install axios
使用 npm:
$ npm install axios
例子
发送一个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:'
// `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, 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:'
// 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*asaxiosfrom'axios';axios.get('/user?id=12345');
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
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
相关阅读:
vue如何使用anmate.css
css的渐变颜色
好用的404组件
解决iview在vue-cli架子中字体图标丢失的方法
以上就是axios怎样基于promise的http请求客户端的详细内容。