3.18

74 阅读1分钟

执行多个并发请求

Promise.all([axios.get(this.url1) , axios.get(this.url2)])

.then(res=>{
  /* 两个请求都执行完毕了再返回结果 */
  console.log(res)
})
axios.all([ axios.get(this.url1) , axios.get(this.url2) ])
.then( axios.spread( (res1,res2)=>{
  /* 两个请求都执行完毕了再返回结果 */
  console.log(res1)
  console.log(res2)
}) )

/* 这个是全局配置,底下methods部分和局部类似,区别已经标注 */
axios.defaults.baseURL = 'http://timemeetyou.com:8889/api/private/v1/';
axios.defaults.headers.common['Authorization'] =localStorage.token;
axios.defaults.timeout = 3000

/* 如果想局部配置,创建一个实例instance通过实例来调接口 */

/* 这个是全局配置的添加请求拦截器 */
/* 每次发送接口都会进行拦截 */
axios.interceptors.request.use(function(config){
  /* console.log('config',config); */
  /* 在请求拦截的时候,添加请求头也是可以的 */
  config.headers.Authorization = localStorage.token;
  /* 必须return */
  return config;
  /* 对错误请求做些什么 */
},function(error){
  return Promise.reject(error)
})


/* 添加响应拦截器,只有请求有响应,都会先走一遍拦截器 */

axios.interceptors.response.use(function(response){
  console.log('response',response);
  /* 可以统一的给返回数据 再加属性和值 */
  response.data.msg="aaaaaa"      
  /* 必须return */
  /* 可以在响应拦截里面直接把data返回出去 */
  return response.data;
  /* 对错误请求做些什么 */
},function(error){
  return Promise.reject(error)
})




  /* 局部配置 axios 实例*/
 /* 自定义配置新建一个 axios 实例 */
/* 设置了baseURL使用了这个instance实例都不用把url写全了,直接写路径(例如:login)即可 */
// this.instance = axios.create({
//   baseURL:'http://timemeetyou.com:8889/api/private/v1/',
//   /* 如果请求花费了超过 `timeout` 的时间,请求将被中断 */
//   timeout: 3000,
//   /* 给使用instance这个实例的接口都配置上headers ,注意是get请求这么用的*/
//   headers:{
//     "Authorization":localStorage.token
//   }
// })

},