vue封装axios

axios.js

import Vue from 'vue'
import qs from 'qs'
import axios from 'axios'

axios.defaults.baseURL = 'http://shuzishijie_api.heyehang.com/';
//'http://127.0.0.1:8081/';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
/**http request 请求拦截器**/
axios.interceptors.request.use(
  req => {
    let method = (req.method).toLocaleLowerCase();
    req.data = qs.stringify(req.data);//传入的值必须进行转换
    if (method == "get") {
      //Get请求
      req.headers = {
        'Content-Type': 'application/x-www-form-urlencoded;'
      }
    } else {
      req.headers = {
        'Content-Type': 'application/x-www-form-urlencoded;'
      }
    }
    return req;
  },
  err => {
    return Promise.reject(err);
  }
);

/**http response 响应拦截器 非必要**/
axios.interceptors.response.use(
  res => {
    // console.log(res);
    if (res.status != 200) {
      //做一些错误处理,如跳转到登录页等
    }
    return res.data;
  },
  err => {
    return Promise.reject(err.response);
  }
);

/**post请求**/
Vue.prototype.$post = function (url = "", data = {}) {
  return axios.post(url, data);
};

/**get请求**/
Vue.prototype.$get = function (url = "", data = {}) {
  // data = qs.stringify(data);
  return axios.get(url, {
    params: data
  });
};
/**delete请求**/
Vue.prototype.$remove = function (url = "", data = {}) {
  return axios({
    url,
    method: 'delete',
    data: data
  })
};
Vue.prototype.$axios = axios;
原文地址:https://www.cnblogs.com/zhizou/p/11647748.html