vue 请求配置

2019-04-10  本文已影响0人  Light_boy

vue项目配置请求接口

const Axios = axios.create({

  baseURL: process.env.BASE_API, // api 的 base_url

  timeout: 10000,

  responseType: 'json',

  withCredentials: true, //携带cookie

  headers: {

    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;application/json'

    // 'Content-Type': 'application/json;charset=utf-8

    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'

  }

})

//请求拦截

Axios.interceptors.request.use(config => {

  config.data = qs.stringify(config.data) //参数格式化

  return config

},err => {

})

//响应拦截

Axios.interceptors.response.use(

  /**

  * 下面的注释为通过在response里,自定义code来标示请求状态

  * 当code返回如下情况则说明权限有问题,登出并返回到登录页

  * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中

  * 以下代码均为样例,请结合自生需求加以修改,若不需要,则可删除

  */

  response => {

    const res = response.data

    if (res.code === 10) {

      Message({

        // message: '登录已过期,请重新登录!',

        message: `${res.message}`,

        type: 'error',

        duration: 5 * 1000   //持续时间

      })

      setTimeout(() => {

        router.push({path: '/login'})

      }, 5000)

      //    //比如50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;

      //    if (res.code === 50008 || res.code === 50012 || res.code === 50014) {

      //      // 请自行在引入 MessageBox

      //      // import { Message, MessageBox } from 'element-ui'

      //      MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {

      //        confirmButtonText: '重新登录',

      //        cancelButtonText: '取消',

      //        type: 'warning'

      //      }).then(() => {

      //        store.dispatch('FedLogOut').then(() => {

      //          location.reload() // 为了重新实例化vue-router对象 避免bug

      //        })

      //      })

      //    }

      return Promise.reject('error')

      //  } else {

      //    return response.data

    } else {

      store.dispatch('setLoading', false)

      return response

    }

  },

  error => {

    console.log('err' + error) // for debug

    // Message({

    //  message: error.message,

    //  type: 'error',

    //  duration: 5 * 1000

    // })

    store.dispatch('setLoading', false)

    return Promise.reject(error)

  }

)

上一篇 下一篇

猜你喜欢

热点阅读