zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    python依赖包整体迁移方法
    ubuntu关于ssh协议登录问题
    k8s部署02-----kubeadm部署k8s
    k8s部署01-----what is k8s?
    兼容到ie10的js文件导出、下载到本地
    webstorm减少内存占用
    foxmail占cpu 100%解决办法
    原生js返回顶部
    js字符串驼峰和下划线互相转换
    element-ui的rules中正则表达式
  • 原文地址:https://www.cnblogs.com/zhizou/p/11647748.html
Copyright © 2011-2022 走看看