Axios -- 項目中應用(攔截器、方法簡單封裝)

src目錄下新建axios文件夾,axios目錄下新建index.js文件

/**
 * axios 網絡請求封裝
 */
import axios from 'axios';
import Vue from 'vue';
import url from '../conf/http_conf';
import store from '../store';

const port = '';
const httpUrl = url + (port == '' ? '' : (':' + port)) + '/';

const instance = axios.create();

instance.defaults.baseURL = httpUrl;

// const isFormData = (v) => {
//     return Object.prototype.toString.call(v) === '[object FormData]';
// };

/**
 *axios 全局 攔截器
 */
instance.interceptors.response.use(function (response) {
    // 這裏統一處理服務器code

    const Code = response.data.code;

    if (Code === undefined) {
        return response.data;
    }

    if (Code.toString().length === 3) {
        if (Code === 200) {
            return response.data.data;
        } else if (Code == 501) {
            console.error('後臺服務出錯');
            return Promise.reject(response.data);
        }
    } else if (Code.toString().length === 5) {
        // 自定義錯誤碼
        if (Code === 25030) {
            Vue.prototype.$token = localStorage.token = '';

            store.commit('setToken', '');
            store.commit('setLoginStatus', false);

            // if (needAuth) {
            //     //判斷該頁面是否需要登錄狀態
            //     console.error('登錄過期了');
            //     router.push({
            //         path: '/Login'
            //     });
            // }
            return Promise.reject(response.data);
        }
        // console.error('[' + Code + ']' + response.data.message);
        return Promise.reject(response.data);
    }
}, function (error) {
    console.error('網絡出錯了!');
    return Promise.reject(error.response.data);
});

/**
 * Request
 * @param {String} url
 * @param {Object} options request參數
 * @param {Boolean} tokenFlag 是否置入token,默認爲true
 */
export const request = (url, options = {}, tokenFlag = true) => {
    if (tokenFlag) {
        // 置入token
        options.headers = {
            'token': Vue.prototype.$token,
            'uKey': Vue.prototype.$uKey
        };
    }
    options = {
        url,
        ...options
    };
    return instance.request(options);
};

/**
 * POST
 * @param {String} url
 * @param {Object} data data參數
 * @param {Boolean} tokenFlag 是否置入token,默認爲true
 */
export const POST = (url, data = {}, tokenFlag = true) => {
    const options = {};
    if (tokenFlag) {
        // 置入token
        options.headers = {
            'token': Vue.prototype.$token,
            // 'Content-Type': 'application/x-www-form-urlencoded'
            'Content-Type': 'application/json',
            'requestType': '1',
            'uKey': Vue.prototype.$uKey
        };
    }
    // if (!isFormData(data)) data = qs.stringify(data);
    return instance.post(url, data, options);
};

/**
 * GET
 * @param {String} url
 * @param {Object} data data參數
 * @param {Boolean} tokenFlag 是否置入token,默認爲true
 */
export const GET = (url, options = {}, tokenFlag = true) => {
    if (tokenFlag) {
        // 置入token
        options.headers = {
            'token': Vue.prototype.$token,
            'Content-Type': 'application/x-www-form-urlencoded',
            'uKey': Vue.prototype.$uKey
        };
    }
    return instance.get(url, options);
};

/**
 * PUT
 * @param {String} url
 * @param {Object} data data參數
 * @param {Boolean} tokenFlag 是否置入token,默認爲true
 */
export const PUT = (url, params = {}, tokenFlag = true) => {
    const options = {};
    if (tokenFlag) {
        // 置入token
        options.headers = {
            'token': Vue.prototype.$token,
            'uKey': Vue.prototype.$uKey
        };
    }
    return instance.put(url, params, options);
};

/**
 * DELETE
 * @param {String} url
 * @param {Object} data data參數
 * @param {Boolean} tokenFlag 是否置入token,默認爲true
 */
export const DELETE = (url, params = {}, tokenFlag = true) => {
    const options = {
        data: params
    };
    if (tokenFlag) {
        // 置入token
        options.headers = {
            'token': Vue.prototype.$token,
            'uKey': Vue.prototype.$uKey
        };
    }
    return instance.delete(url, options);
};

controller中使用

import {request, POST ,GET} from '@/axios/index';

const A_HANDLE = 'A-handle';
/**
 * 我的首頁接口
 */

class name{
    // 調用POST方法
    apiPostMethod (params) {
        return POST(`${A_HANDLE }/api/xxxxxx`, params).then(res =>             
        res);
    };
    apiGetMethod () {
        return GET(`${A_HANDLE }/api/xxxxxx`, {}, false).then(res =>         
        res)
    }
    /**
     * 異步上傳圖片返回圖片地址
     * @return {Promise}
     */
    uploadImage (file) {
        const formData = new FormData();
        formData.append('file', file);
        return request(`${A_HANDLE }/console/uploadImage`, {
            method: 'post',
            data: formData
        }).then(res => res);
    }
}

const controller = new name();

export default controller;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章