axios傳參/響應結果/全局配置/攔截器


axios傳參

GET傳參

通過URL傳遞參數

axios.get('/data?id=123')
     .then(ret=>{
      console.log(ret.data)
     })

restful形式的url傳參

axios.get('/data/123')
     .then(ret=>{
      console.log(ret.data)
     })

params傳參

axios.get('/data',{
    params:{
      id:123
      }
    })
    .then(ret=>{
      console.log(ret.data)
    })

 DELETE傳參(與GET類似)

通過URL傳遞參數

axios.delete('/data?id=123')
     .then(ret=>{    console.log(ret.data) })

restful形式的url傳參

axios.delete('/data/123')
     .then(ret=>{    console.log(ret.data) })

params傳參

axios.delete('/data',{
    params:{
      id:123 } }) .then(ret=>{    console.log(ret.data) })

 POST傳參

通過選項傳遞參數(默認傳遞的是json格式的數據)

axios.post('/data',{
      uname: 'tom',
      pwd: '123'
     })
     .then(ret=>{
      console.log(ret.data)
     })

 通過URLSearchParams傳遞參數(application/x-www-form-urlencoded)

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/data',params).then(ret=>{
      console.log(ret.data)
     })

PUT傳參(與post類似)

通過選項傳遞參數(默認傳遞的是json格式的數據)

axios.put('/data',{
      uname: 'tom',
      pwd: '123'
     })
     .then(ret=>{
      console.log(ret.data)
     })

 

post與put都支持兩種格式的參數傳遞,一種是json,一種是表單
用哪一種取決於后台(后端),json更方便一些

 

響應結果

data:實際響應回來的數據
headers:響應頭信息
status:響應狀態碼(200正常的)
statusText:響應狀態信息

axios.post('/data')
     .then(ret=>{
      console.log(ret)
     })

ret就是axios包裝后的響應結果

 

 

全局配置

axios.defaults.timeout = 3000;   //超時時間

axios.defaults.baseUrl = "http://locahost:3000/app";   //默認地址

axios.defaults.headers['mytoken'] = "asdqwe123qw4e5qe6wqe3";   //設置請求頭

 

常用設置默認地址與設置請求頭

 

攔截器

請求攔截器(在請求發出之前設置一些信息)

請求攔截器設置請求頭更加靈活
axios.interceptors.request.use(function(config){
    //在請求發出之前進行一些信息設置,將請求頭中的 mytoken 設置為了 asdqwe123qw4e5qe6wqe3
    config.headers.mytoken = 'asdqwe123qw4e5qe6wqe3'
    return config;
},function(err){
    //處理響應的錯誤信息
})

 

 響應攔截器(在獲取數據之前對數據做一些加工處理)

axios.interceptors.response.use(function(res){
    //res是axios所包裝的數據,包含data,headers,status,statusText
    //在這里對返回的數據進行處理
    return res;
},function(err){
    //處理響應的錯誤信息
})

 

使用響應攔截器后調用接口中.then得到的數據就是實際數據

axios.interceptors.response.use(function(res){
    //在這里對返回的數據進行處理
    var data = res.data
    return data;        //使用后調用接口中then得到的數據就是實際數據
},function(err){
    //處理響應的錯誤信息
})

 


免責聲明!

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



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