vue(nuxt同理)项目中配置axios全局统一拦截器

一:新建util文件夹,并且新建axios.js文件如下图:

vue(nuxt同理)项目中配置axios全局统一拦截器_第1张图片

import axios from 'axios'
import {Message, MessageBox, Notification} from 'element-ui'

const service = axios.create({
  baseURL: `http://${process.env.BASE_URL || 'localhost'}:${process.env.PORT || 3001}`,
  timeout: 10000,
  headers: {}
});

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (config.url == undefined) {
    Notification({
      title: '警告',
      message: '请求路径错误,请检查!',
      type: 'warning',
      offset: 100,
      duration: 2000
    });
    return false
  }
  // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  //config.headers['X_Innovate_Session'] = getToken() 
  // config.headers['X_Token'] = getToken()
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里,自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题,登出并返回到登录页
   * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例,请结合自生需求加以修改,若不需要,则可删除
   */
  response => {
    const res = response.data
    if (response.status == 200 && res.code === '0000') {
      return res
    } else {
      if (res.code === '401') {
        Message.warning('登录过期,请重新登录!')

      } else {
        Message.error(res.msg)
      }
      // return Promise.reject('error')
    }
  },
  /**
  *	错误回调
  *	*/
 
  error => {
    console.error('err:' + error) // for debug
    if (error.request.status == '401') {
      Message.warning('登录过期,请重新登录!')

    } else if (error.request.status == '404') {
      Message({
        message: '错误的请求!',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.request.status == '500') {
      Message({
        message: '服务器异常!',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: 'err请求失败',
        type: 'error',
        duration: 5 * 1000
      })
      //router.push({ path: '/404' })
      return Promise.reject(error)
    }
  })

export default service;

二:创建接口文件并且导入刚才封装的axios文件

import request from '../utils/axios'
export default {
	register:function (data) {
    return request({
      url: `${users}/register`,
      method: 'post',
      data
    })
  }
  *//To do something*
  *
  *
}

三:组件内调用封装的接口

import userApi from '../../../interface/user'

  export default {
    data() {
      return {
        user: ''
      }
    },
    async mounted() {
      const {data: {user}} = await userApi.getUser()
      this.user = user
    }
  }

你可能感兴趣的:(前端)