其他分享
首页 > 其他分享> > axios二次封装

axios二次封装

作者:互联网

import axios from 'axios';
import qs from 'qs';
import { Message} from '@alifd/next';

//默认地址
const request = axios.create({
    timeout: 100000,
    baseURL:'http://192.168.1.193:8083/quick-platform/' //
});

const parse = (data) => {
    const result = {};
    for (const key in data) {
        if (typeof data[key] === 'string') {
            result[key] = data[key]
        } else {
            result[key] = JSON.stringify(data[key])
        }
    }
    return qs.stringify(result);
}

const networkErrorMap = {
    error: 'Network Error',
    400: '请求错误',
    401: '未授权,请登录',
    403: '拒绝访问',
    404: '请求地址不存在',
    408: '请求超时',
    500: '服务器内部错误',
    501: '服务未实现',
    502: '网关错误',
    503: '服务不可用',
    504: '网关超时',
    505: 'HTTP版本不受支持'
}

// 添加拦截器
request.interceptors.request.use((config) => {
    const token = localStorage.getItem("token")
    console.log(token,'qqqqqqqqqqqqqq')
    if (token) {
        config.headers['X-Access-Token'] = token
    }
    return config
}, error => {
    return Promise.reject(error);
})

//响应器
request.interceptors.response.use(function (response) {
    const { code, success, result, message } = response.data;
    if (success) {
        return response.data;
    } else {
        return Promise.reject(message);
    }
}, function (err) {
    if (err && err.response && err.response.status) {
        err.message = networkErrorMap[err.response.status] || err.message
    }
    return Promise.reject(err)
});


function base(type,returnRes="") {
    return function (url, data, config) {
        const { showError = true, headers = {}, json = true} = config || { showError: true, headers: {}, json: true };
        const params = {
            url,
            method: type,
            headers
        };
        if (['post', 'put'].includes(type)) {
            if (!json) {
                params.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
            }
            params.data = json ? data : parse(data);
        } else {
            params.params = data
        }
        if(returnRes == "postfile"){
            params.headers['Content-Type']="multipart/form-data";
        }
        return request(params)
            .catch((e) => {
                showError && Message.error(e);
                return Promise.reject(e)
            })
    }
}
export const get = base('get');
export const deletes = base('delete');
export const post = base('post');
export const put = base('put');
export const postfile = base('post','postfile');

 

//使用

import { get, post, put } from './http';

//测试
export function GetcustomPageList(data) {
    return get('/customPage/list', data);
}

 

标签:axios,const,err,二次,return,params,封装,data,response
来源: https://www.cnblogs.com/wangshengli520/p/16254935.html