在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ 用axios封裝http請(qǐng)求時(shí),怎樣做判斷自定義狀態(tài)值成功后對(duì)應(yīng)的操作?

用axios封裝http請(qǐng)求時(shí),怎樣做判斷自定義狀態(tài)值成功后對(duì)應(yīng)的操作?

以前在ajax中可以這樣處理

request(param){
    $.ajax{
        type: param.type,
        url: param.url,
        success(res){
            if(res.status === 0){
                typeof param.success === 'function' && param.success(res.data)
            }else if(res.status === 1){
                login()        
            }else if(res.status === 2){
                typeof param.success === 'function' && param.success(res.data)
            }
        },
        error(err){
            typeof param.error === 'function' && param.error(res.err)
        }
    }
} 
   

像上面這種情況,比如狀態(tài)為0表示成功,然后進(jìn)行成功后的處理,這在axios中怎么處理呢?

回答
編輯回答
忘了我

可以添加一個(gè)響應(yīng)攔截器

const instance = axios.create()
// 添加一個(gè)響應(yīng)攔截器
instance.interceptors.response.use(response => {
  window.vm.$loading.hide()
  // 在這里對(duì)返回的數(shù)據(jù)進(jìn)行處理
  let status = response.status
  let data = response.data
  if (status === 200) {
    if (data.code !== '0000') {
      window.vm.$alert({
        msg: data.desc,
        type: 'danger'
      })
    }
    return Promise.resolve(data)
  } else {
    return Promise.reject(response)
  }
}, error => {
  // response error
  console.log(error)
  window.vm.$loading.hide()
  window.vm.$alert({
    msg: '請(qǐng)求異常,請(qǐng)聯(lián)系管理員!',
    type: 'danger',
    autoClose: false
  })
  return Promise.reject(error)
})
export default instance
2018年2月10日 17:32
編輯回答
失魂人
async function request(param) {
    let { url, method, success, error } = param
    try {
        let { data, status, error } = await axios({ method, url })
        if (status === 0) {
            typeof success === 'function' && success(data)
        } else if (status === 1) {
            login()
        } else if (status === 2) {
            typeof success === 'function' && success(data)
        }
    } catch (err) {
        typeof error === 'function' && error(err)
    }
}
2017年6月25日 18:02
編輯回答
獨(dú)特范
axios(url, options)
    .then(res => {
        if (res.status === 1) {
            return res.data;
        }
        // 其他類(lèi)似
    })
    .catch(console.error.bind(console))
2017年1月28日 16:46
編輯回答
淺時(shí)光
http.post = (url, data) => {
  return new Promise((resolve, reject) => {
        axios.post(requestUrl + url, qs.stringify(data),{
          headers: {
              
          }
      }).then(res => {
          if (res.status === 200) {
            resolve (res.data)
          } else {
            alert ('request failed, please try again later')
          }
      })
  })
}; 

是這個(gè)意思嘛?

2018年5月3日 19:28
編輯回答
有你在
import axios from 'axios'

//請(qǐng)求攔截
axios.interceptors.request.use(function(config){
    ...
    return config
})

//響應(yīng)攔截
axios.interceptors.response.use(function(config){
    ...    
    return config
})
2017年12月9日 19:08