axios用法

1. 设置默认头信息

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

2. 创建请求拦截器 (POST请求配合QS)

// http request 拦截器
axios.interceptors.request.use(config => {
  if (config.method === 'post') {
    config.data = qs.stringify(config.data, {arrayFormat: 'brackets'})
  }
  return config
})

3. 创建响应拦截器 (使用Element UI提示错误信息)

// http response 拦截器  与后台提前定义正确code 错误的提示
axios.interceptors.response.use(
  response => {
    if (response.data.code === '200') {
      return response.data.data
    } else if (response.config.responseType === 'blob') {
      return response
    } else {
      Message.error(response.data.msg)
      return Promise.reject(response.data.msg)
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 跳转到登录页面
          router.push({
            path: '/login'
          })
          break
        case 500:
          router.push({
            path: '/error/500'
          })
          break
        case 404:
          router.push({
            path: '/error/404'
          })
          break
        case 504:
          router.push({
            path: '/error/504'
          })
          break
      }
    }
    return Promise.reject(error.response.data)
  }
)

4. 使用get/post请求

// get请求
axios.get(`${base}/user/updatePwd`, {params: params})

// post请求
axios.post(`${base}/login`, params)

5. 使用axios post下载excel

axios.post(`${base}/auth/export`, params, {
    responseType: 'blob'
  }).then(res => {
    if (res.data) {
      if ('msSaveBlob' in navigator) { // 对IE和Edge的兼容
        window.navigator.msSaveBlob(res.data, decodeURI(res.headers['content-disposition'].split('filename=')[1]))
      } else {
        let blob = res.data
        let a = document.getElementById('exportLog')
        let url = window.URL.createObjectURL(blob)
        let filename = decodeURI(res.headers['content-disposition'].split('filename=')[1])
        var evt = document.createEvent('HTMLEvents') // 对firefox的兼容
        evt.initEvent('click', false, false) // 对firefox的兼容
        a.href = url
        a.download = filename
        a.dispatchEvent(evt) // 对firefox的兼容
        a.click()
        window.URL.revokeObjectURL(url)
      }
    }
  })

你可能感兴趣的:(JavaScript,Blob,axios,vue)