axios.js 861 Bytes
import axios from 'axios';
import router from '../router';
import _ from 'lodash'
import qs from 'Qs'

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 发送请求前
    if (config.method === 'post') {
      // POST PHP需要修改数据格式
      config.data = qs.stringify(config.data)
    }
    // 绑定默认请求头
    config.params = _.merge(config.params, {
      f: 'voice',
      client_id: '313939'
    })
    return config;
  },
  error => {
    // 请求错误处理
    return Promise.reject(error);
  });

// 响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.code === 401) { // 未授权跳转登录页
      router.replace({
        path: '/auth'
      });
    }
    return response;
  },
  error => {
    return Promise.reject(error.response.data);
  });

export default axios;