当前位置:   article > 正文

axios拦截配置及使用(文件下载)_axios 拦截器文件下载

axios 拦截器文件下载


默认配置

import axios from 'axios'
axios.defaults.withCredentials = true // 是否在跨域请求中携带凭证(如 cookie)
axios.defaults.timeout = 10000 // 设置超时时间
axios.defaults.headers.common['Content-Type'] = 'application/json' // common全局通用配置
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
const context = 'fuwuqi'
const apis = {
  /**
   * @Description: 用户管理
   */
  getUserInfo: `${context}/user/getUserInfo`
}
export { apis, axios }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

请求拦截

import { useSystemStore } from '@/stores/system'
axios.interceptors.request.use(
  function (config) {
    config.headers['test'] = 0 // 1:开 0:关
    config.headers['tenantId'] = systemStore.tenantId // 租户id
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

响应拦截

axios.interceptors.response.use(
  function (response) {
    if (response && response.data && (response.data.flag || response.data.success)) {
       // 具体情况修改上述的条件 		
      if (response.data.ret !== 302) {
         return response.data
      }    
       localStorage.setItem('login', false)
       console.log(('接口302' + response?.data?.redirectUrl))
       if (import.meta.env.PROD && response?.data?.redirectUrl) {
       //判断是否在生产环境import.meta.env.PROD
         window.location.href = response.data.redirectUrl
       }
       return null
    } else {
      // 直接返回的数据,如文件等
      if (Object.prototype.toString.call(response.data) === '[object Blob]') {
        return response
      }
      ElMessage.error(response?.data?.message ?? '请求接口错误!')
      return null
    }
  },
  function (error) {
    ElMessage.error(error.message || '服务器出错!')
    return Promise.reject(error)
  }
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

使用实例1—正常情况(成功或失败)

具体使用get、post等,可参考文章 axios的get和post请求传headers、query、body等参数

  import { axios, apis } from '@/request'
  async function save(id) {
    const result = await axios.post(
      apis.saveInfo,
      { id: id},
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      }
      // 若请求头为默认的'application/json' , 则不用传上述的对象
    )
    if (result) {
      console.log('接口请求成功')
    }
    // 错误会直接拦截,此时返回的result为null
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

使用实例2—返回为文件流

此时result的data为文件流

  import { axios, apis } from '@/request'
  async function save(id) {
    const result = await axios.post(
      apis.download,
      { id: id},
      { responseType: 'blob' }
    )
    if (result.data) {
      console.log('接口请求成功')
      // 下载文件
      const blob = result.data;// 可以通过 new Blob([{id:'121'}]) 生成blob
	  const elink = document.createElement('a') // 创建a标签
	  elink.href = window.URL.createObjectURL(blob)
	  elink.download = 'fileName.txt' // 文件名
	  elink.style.display = 'none'
	  document.body.appendChild(elink)
	  // link.target = '_blank' // 打开新的标签页
      elink.click()
	  URL.revokeObjectURL(elink.href)
	  document.body.removeChild(elink)
    }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/227765
推荐阅读
相关标签
  

闽ICP备14008679号