美文网首页
request.js

request.js

作者: 懒懒猫 | 来源:发表于2022-09-02 14:52 被阅读0次

    request.js

    import axios from 'axios'
    import storage from 'store'
    // import router from '@/router'
    import notification from 'ant-design-vue/es/notification'
    import qs from 'qs'
    import { ACCESS_TOKEN } from '@/store/mutation-types'
    // 创建 axios 实例
    const request = axios.create({
      // API 请求的默认前缀
      baseURL: process.env.VUE_APP_PREVIEW === 'true' ? '/api' : process.env.VUE_APP_API_BASE_URL,
      timeout: 30000 // 请求超时时间
    })
    
    // request interceptor
    request.interceptors.request.use(config => {
      const token = storage.get(ACCESS_TOKEN)
      // 如果 token 存在
      // 让每个请求携带自定义 token 请根据实际情况自行修改
      if (token) {
        config.headers['Authorization'] = token
      }
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    })
    
    // response interceptor
    request.interceptors.response.use(
      response => {
        // return response.data
        const res = response.data || {}
    
        if (!res.success) {
          // 401: Unauthorized
          if (res.code === 401 || res.code === 501 || res.code === 402) {
            notification.error({
              key: 'Unauthorized',
              message: '错误',
              description: '身份验证失败,请重新登陆'
            })
            // 从 localstorage 获取 token
            this.$store.commit('SET_TOKEN', '')
            storage.remove(ACCESS_TOKEN)
          //   const token = storage.get(ACCESS_TOKEN)
          //   if (token) {
          //     store.dispatch('Logout').then(() => {
          //       window.location.reload()
          //     })
          //   }
          }
    
          return Promise.reject(response)
        } else {
          return res
        }
      },
      error => {
        return Promise.reject(error)
      }
    )
    
    export default {
      /**
       *
       * @param {String} url
       * @param {Object} data
       * @param {String} isForm
       * @param {Object} config
       *
       * 这里是通用请求
       * 如果需要特殊的配置在config中配置
       *
       */
      post (url, data, isForm, config = {}) {
        if (isForm === 'FORM') {
          const formHeaders = {
            // 'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
          }
          const transformRequest = data =>
            qs.stringify(data, {
              encode: false,
              allowDots: true,
              arrayFormat: 'indices'
            })
          config.transformRequest = config.transformRequest ? [transformRequest, ...config.transformRequest] : [transformRequest]
    
          config = { headers: formHeaders, ...config }
        }
        // 文件上传
        if (isForm === 'FILE') {
          const formHeaders = {
            'Content-Type': 'multipart/form-data'
          }
          config = { headers: formHeaders, ...config }
          const forms = new FormData()
          forms.append('file', data)
          data = forms
        }
        return request.post(url, data, config)
      },
      /**
       *
       * @param {String} url
       * @param {Object} params
       */
      get (url, params, config) {
        return request.get(url, { params: params }, config)
      },
      put (url, data, isForm, config = {}) {
        if (isForm === 'FORM') {
          const formHeaders = {
            // 'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
          }
          const transformRequest = data =>
            qs.stringify(data, {
              encode: false,
              allowDots: true,
              arrayFormat: 'indices'
            })
          config.transformRequest = config.transformRequest ? [transformRequest, ...config.transformRequest] : [transformRequest]
    
          config = { headers: formHeaders, ...config }
        }
        return request.put(url, data, config)
      }
    }
    
    
    

    相关文章

      网友评论

          本文标题:request.js

          本文链接:https://www.haomeiwen.com/subject/pjtynrtx.html