美文网首页
手写axios拦截器

手写axios拦截器

作者: A郑家庆 | 来源:发表于2021-07-22 19:50 被阅读0次
    import {Message} from 'element-ui'
    import axios from 'axios'
    import {router} from '../router'
    function request (url, data={}, method="get", options, responseType) {
      let axios = createAxiosInstance(options)
      return axios({
        url,
        data: method.toLowerCase() === 'get' ? {} : data,
        params: method.toLowerCase() === 'get' ? data : {},
        method: method.toLowerCase(),
        responseType: responseType || 'json'
      })
    }
    
    function createAxiosInstance (options) {
      let instance = axios.create({
        timeout: 5000,
        withCredentials: true,
        header: Object.assign({
          'X-Request-With': 'XMLHttpRequest',
          'Content-Type': 'application/json;charset=UTF-8'
        })
      })
      instance.interceptors.request.use(
        config => config,
        error => Promise.reject(error)
      ),
      instance.interceptors.request.use(
        response => {
          let res = response.data
          if (res.code === 0) return res
          else Message({
            message: res.message,
            type: 'error',
            duration: 5000
          })
        },
        error => {
          if (error.errorCode === 401) return router.psuh('/login')
          else Message({
            message: error.message,
            type: 'error',
            duration: 5000
          })
        }
      )
      return instance
    }
    
    export default request
    

    相关文章

      网友评论

          本文标题:手写axios拦截器

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