局部配置axios实例化对象

193 阅读1分钟

created(){

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

},

methods:{

login(){
  this.instance.post('login',{
    username:'admin',
    password:'123456'
  })
  .then(res=>{
    localStorage.token = res.data.data.token;
  })
},
getUser(){
  this.instance.get('users',{
    params:{
      pagenum:1,
      pagesize:5
    },
    /* 在get请求中单独配置headers这样配置 */
    // headers:{
    //   "Authorization":localStorage.token
    // }
  })
  .then(res=>{
    console.log(res.data)
  })
},
getList(){
  this.instance.get('rights/list')
  .then(res=>{
    console.log(res)
  })
}

}