axios的常用方法


執行get請求

 axios.get("url?id=13",{
    /*params:{
      name:123 //帶參請求
    }*/
    })
    .then(res=>{
       //成功后執行
    }) 
    .cache(err=>{
      //錯誤執行
    }) 
    .finally(function(){
      //總是執行
     })

執行post請求

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

執行並發請求

function getUserAccount(){
    return axios.get("/user/12");
  }
  function getUserPermissions(){
    return axios.get("/user/123/permission")
  }
  axios.all([getUserAccount(),getUserPermissions()])
    .then(axios.spread(function(acct,perms){
      //兩個請求都成功
    }))

通過傳遞相關配置來進行請求

//post請求 
 axios({
    method:'post',
    url:'',
    data:{
      firstName:'M',
      lastName:'t'
    }
  })
//get請求
 axios({
    method:'get',
    url:'',
    responseType:'stream'
  })
    .then(function(response){
        response.data.pipe(fs.createWriteStream('a.jpg'))
    })

創建實例

const instance = axios.create({
  baseURL:'',//方便的設置路由的轉發規則
  headers:{"X-Custom-header":foobar}//通過請求頭設置一些信息
    
})

攔截器interceptors

配置攔截器,對請求與響應進行處

// 添加請求攔截器
axios.interceptors.request.use(function (config) {  
  //發送請求之前做一些事情
    return config;
  }, function (error) {
   //捕捉錯,對錯誤進行處理
    return Promise.reject(error);
  });

// 添加響應攔截器
axios.interceptors.response.use(function (response) {
    //對響應結果做一些處理
  /*
    if(data.code===200){
      return data.data
    }else{
     return response 
    }
  */
    return response;
  }, function (error) {
    return Promise.reject(error);
  });

 

params 的用法

let params = {
    keyWord: null,
    name: 'xxx',
    age: 22
}
// 為 null 的屬性都會被過濾掉,最終的請求 url 是 /person?name=xxx&age=22
instance.get('/person', { params })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM