vue.$http: vue 2.0以后不对vue-resource进行维护,无法对请求进行取消

axios:可以进行手动取消请求,复用性好

axios二次封装使用

大概流程:

  1. 引入 vue 和 axios
  2. 定义类class Ajax{}
  3. 构造函数(constructor)里写初始化事件
    (1). 重写methods方法
    (2). 请求拦截(接口地址进行处理), 响应拦截(成功失败信息)
    4.导出axios

业务使用:
定义一个api挂载到全局vue.prototype, 然后业务 this.$api访问

api内容:

每个模块定义一个index.js 包含当前模块所有的请求
import axios from ‘util/axios’
axios.post(ur;, data);

外面接口层导出各个模块

import Vue from 'vue';
import Axios from 'axios';

class Ajax {
	constructot () {
		this.axios = Axios;
        this.token = 'CSRFPreventionToken';
        this.noAuthCode = 401;
        this.successCode = 0;

        this.initAxios();
	}

	initAxios () {
        this.axios.defaults.baseURL = '/test';
        this.axios.defaults.headers.common[this.token] = '值';
        this.axios.defaults.timeout = 60000;
        this.rewriteMethods();
        this.reqInterception();
        this.resInterception();
    }
	rewriteMethods () {
        ['get', 'head', 'jsonp'].forEach(method => {
            this.axios[method] = (url, data, options = {}) => {
                let params = [];
                if (data) {
                    for (let key in data) {
                        if (data.hasOwnProperty(key)) {
                            params.push(key + '=' + encodeURIComponent(data[key]));
                        }
                    }
                }

                if (url.indexOf('?') === -1) {
                    url += '?' + params.join('&');
                } else {
                    url += '&' + params.join('&');
                }

                if (url && typeof url === 'string') {
                    Object.assign(options, { url, method });
                }

                return this.axios(options);
            };
        });
    }
  //请求拦截器,对地址进行处理

    reqInterception () {
        this.axios.interceptors.request.use(config => {   
            config.url = this.fixURL(config.url);

            // 绝对路径的url不要加baseURL
            if (config.url.slice(0, 1) === '/') {
                config.baseURL = '';
            }

            return config;
        });
    }

    //   响应拦截器,对成功响应数据进行处理
    
    resInterception () {
        this.axios.interceptors.response.use(
            this.successHandle.bind(this), 
            this.errorHandle.bind(this)
        );
    }

    successHandle (response) {
        const URL = response.config.url;
        const STATUS = response.status;
        let data = response.data || {};

        data.status = STATUS;

        if (!data.success) {
            // 抛出报错信息,包括接口名,接口返回的数据
            Promise.reject({
                url: URL,
                data
            });
        }

        return data;
    }

    errorHandle ({config, response}) {
        const MSG = typeof STATUS_MAP[response.status] === 'function' ? STATUS_MAP[response.status](config.url) : STATUS_MAP[response.status];
        const ERROR = {
            success: false,
            status: response.status,
            msg: MSG || response.data
        };
        Vue.prototype.$showErr(ERROR.msg);
        return Promise.reject(ERROR);
    }

}

export default new Ajax().axios;
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐