封装axios 使用jsonbig解决长数值精度丢失问题

vue yekong

安装依赖

npm i JSONbig --save

在axios.create添加

const service = axios.create({
    baseURL: devIp + '', // 测试IP
    timeout: 100000, // request timeout,
    transformResponse: [function (data) {
        try {
            // 如果转换成功则返回转换的数据结果
            return JSONbig.parse(data)
        } catch (err) {
            // 如果转换失败,则包装为统一数据格式并返回
            return {
                data
            }
        }
    }]
});
import axios from 'axios';
import {ElMessage} from 'element-plus'
import {devIp} from '@/api/ipConfig';
import router from "@/router";
import JSONbig from 'json-bigint'

const service = axios.create({
    baseURL: devIp + '', // 测试IP
    timeout: 100000, // request timeout,
    transformResponse: [function (data) {
        try {
            // 如果转换成功则返回转换的数据结果
            return JSONbig.parse(data)
        } catch (err) {
            // 如果转换失败,则包装为统一数据格式并返回
            return {
                data
            }
        }
    }]
});

// request interceptor
service.interceptors.request.use(config => {
    let uid = sessionStorage.getItem('token');
    if (uid) {
        config.headers['token'] = uid; // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config;
}, error => {
    Promise.reject(error);
});

// respone interceptor
service.interceptors.response.use(
    // response => response,
    response => {
        const res = response.data;
        // return res;
        if (res.code == '200') {
            return res;
        } else if (res.code == '401') {
            sessionStorage.removeItem('token')
            router.push({path: '/login'});
            ElMessage({
                message: res.msg,
                type: 'error',
                duration: 2 * 1000
            });
        } else {
            ElMessage({
                message: res.msg,
                type: 'error',
                duration: 5 * 1000
            });
            return res;
        }
    },
    error => {
        console.log('err' + error);// for debug
        ElMessage({
            message: error.message,
            type: 'error',
            duration: 3000
        });
        return Promise.reject(error);
    });

export default service;

喜欢