对axios的理解
axios是基于promise的,可以使用promise api
axios的请求方式
axios(config)
axios.request(config)
axios.get(url [,config])
axios.post(url [,data [,config]])
axios.put(url [,data [,config]])
axios.delete(url [,config])
axios.patch(url [,data [,config]])
axios.head(url [,config])
下面开始axios的案例
对于get请求的案例
//执行GET请求 import axios from 'axios' axios.default.baseURL = 'http://localhost:3000/api/products' axios.get('/user?ID=12345') //返回的是一个Promise .then(res=>console.log(res)) .catch(err=>console.log(err)); //可配置参数的方式 axios.get('/user',{ params:{ ID:12345 } }).then(res=>console.log(res)) .catch(err=>console.log(err));
发送post请求
//发送post请求 axios.post('/user',{ firstName: 'simon', lastName:'li' }).then(res=>console.log(res)) .catch(err=>console.log(err));
并发请求
//发送多个请求(并发请求),类似于promise.all,若一个请求出错,那就会停止请求 const get1 = axios.get('/user/12345'); const get2 = axios.get('/user/12345/permission'); axios.all([get1,get2]) .then(axios.spread((res1,res2)=>{ console.log(res1,res2); })) .catch(err=>console.log(err))
最基本的使用方法
//发送post请求 axios({ method: 'post', //请求方式,默认是get请求 url:'/user/12345', //地址 data:{ //参数 firstName: 'simon', lastName: 'li' } });
创建一个实例
const instance = axios.create({ baseURL: 'http://localhost:3000/api/products', timeout: 1000, headers: {'X-Custom-Header':'foobar'} }); //instance的使用 instance.get('/user',{ params:{ID:12345} }).then(res=>console.log(res)) .catch(err=>console.log(err))
config的配置选项
{ //服务器的地址,是必须的选项 url: '/user', //请求的方式,若没有则默认是get method:'get', //如果url不是绝对地址,则会加上baseURL baseURL: 'http://localhost:3000/', //transformRequest允许请求的数据在发送至服务器之前进行处理,这个属性只适用于put、post、patch方式 //数组的最后一个函数必须返回一个字符串或者一个'ArrayBuffer'或'Stream'或'Buffer' 实例或'ArrayBuffer','Formdata', //若函数中用到了headers,则需要设置headers属性 transformRequest: [function(data,headers){ //根据需求对数据进行处理 return data; }], //transformResponse允许对返回的数据传入then/catch之前进行处理 transformResponse:[function(data){ //依需要对数据进行处理 return data; }], //headers是自定义的要被发送的信息头 headers: {'X-Requested-with':'XMLHttpRequest'}, //params是请求连接中的请求参数,必须是一个纯对象 params:{ ID:12345 }, //paramsSerializer用于序列化参数 paramsSerializer: function(params){ return Qs.stringify(params,{arrayFormat:'brackets'}); }, //data是请求时作为请求体的数据——request.body //只适用于put、post、patch请求方法 //浏览器:FormData,File,Blob;Node:stream data:{ firstName: 'simon', }, //timeout定义请求的时间,单位是毫秒,如果请求时间超过设定时间,请求将停止 timeout:1000, //withCredentials表明跨跨域请求书否需要证明。 withCredentials:false, //默认值 //adapter适配器,允许自定义处理请求 //返回一个promise adapter:function(config){ /*...*/ }, //auth表明HTTP基础的认证应该被使用,并提供证书 auth:{ username:'simon', password:'123456', }, //responseType表明服务器返回的数据类型,这些类型包括:json/blob/document/ arraybuffer/text/stream responseType: 'json', //proxy定义服务器的主机名和端口号 //auth属性表明HTTP基本认证应该跟proxy相连接,并提供证书 //这将设置一个'Proxy-Authorization'头(header),覆盖原来自定义的 proxy:{ host:127.0.0.1, port:8080, auth:{ username:'simon', password:'123456' } }, //取消请求 cancelToken: new CancelToken(cancel=>{}) }
设置默认设置
import axios from 'axios' axios.default.baseURL = 'http://localhost/api/'; axios.default.headers.common['Authorization'] = AUTH_TOKEN;
实例化axios后再添加默认操作,不影响其他axios
const instance = axios.create({ //创建实例时就进行默认设置 baseURL: 'http://localhost:3000/api', }); //在实例外进行默认设置 instance.default.headers.common['Authorization'] = AUTH_TOKEN;
设置优先级--设置是可以被覆盖的,越往后优先级越高,后面会覆盖前面的设置
import axios from 'axios' axios.default.timeout = 1000; //全局默认设置 const instance = axios.create({ timeout: 2000, //实例默认设置 }); //请求时的默认设置 instance.get('/users/123456',{ timeout: 3000, //最后这个设定的时间会生效 }).then(/*....*/).catch(/*....*/)
一个请求的返回信息(响应信息)包括一下信息
{ //data是服务器提供的响应 data:{}, //服务器返回的http状态码 status: 200, //statusText是服务器返回的http状态信息 statusText: 'ok', //heades是服务器响应中携带的headers headers:{}, //config是axios进行的设置,目的是为了请求(request) config:{}, } //使用then后,response中将包含上述信息 axios.get('/user/12345').then(response={ console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); })
对于axios的请求拦截和响应拦截---拦截可以对数据做一些处理,比如给请求数据添加头部信息,或对响应数据进行序列化,然后再传给浏览器,这些都可以在拦截器中进行
在请求拦截中,错误拦截较少,通常都是配置相关的拦截
在响应拦截中,若成功,则主要是对数据进行过滤;若失败,则可以根据starus判断报错的状态码,来跳转到不同的错误提示页面
//添加一个请求拦截器 axios.interceptors.request.use(config=>{ //在请求之前做一些事 return config; },err=>{ //请求错误的时候做一些事 return Promise.reject(err); }); //添加一个响应拦截器 axios.interceptors.response.use(response=>{ //对返回的数据做一些处理 reutrn response; },err=>{ //对返回的错误做一些处理 return Promise.reject(err); });
//移除拦截器 const myInterceptor = axios.interceptors.request.use(config=>{return cofig}) axios.interceptors.request.eject(myInterceptor); //在一个axios实例中使用拦截器 var instance = axios.create(); instance.interceptors.request.use(function(){/*...*/});
错误处理--使用validateStatus设置选项自定义HTTP状态码的错误范围
axios.get('user/12345',{
validateStatus:function(status){
return status < 500;//当返回码小于等于500时视为错误
}
});
取消请求---可以使用cancel token取消一个请求,当用户搜索时,可能需要频繁的发送数据查询请求,因此当发送下一个请求时 ,需要撤销上一个请求。因此需要取消请求。
const CancelToken = axios.CancelToken; //使用CancelToken.source工厂函数创建一个cancel token const source = CancelToken.source(); axios.get('/user/12345',{ cancelToken: source.toke }).catch(thrown=>{ if(axios.isCancel(thrown)){ console.log('Request canceled', thrown.message); }else{ //handle error } }); //取消请求 source.cancel('操作被用户取消');
文章引用:

浙公网安备 33010602011771号