import axios from 'axios'; import { showFailToast } from 'vant'; import { useStore } from '@/pinia/store.js'; import router from '@/router/index'; import { tansParams } from '@/utils/compatible.js'; const pinias = useStore(); // 设置接口超时时间 axios.defaults.timeout = 8000; //http request 拦截器 axios.interceptors.request.use( (config) => { // 配置请求头 config.headers = { 'Content-Type': 'application/json;charset=UTF-8', Authorization: 'Bearer ' + pinias.token, }; return config; }, (error) => { return Promise.reject(error); } ); //http response 拦截器 axios.interceptors.response.use( (response) => { // console.log('request success', response); const { code } = response ? response.data : 'undefined' || ''; if (code == 401) { showFailToast('登录已过期,请重新登录!'); router.push('/login'); return; } // axios单独请求接口时,未返回code情况处理 if (code == undefined) { return response; } // 接口未返回数据时 if (!!!code) { showFailToast('数据请求失败,请稍后再试!'); pinias.hideLoading(); return false; } if (code != 200) { showFailToast(response.data.message || response.data.msg || ''); } return response; }, (error) => { console.log('request error:', error); pinias.hideLoading(); showFailToast('网络连接异常,请稍后再试!'); } ); // 封装 GET POST 请求并导出 export default function request(config) { // get请求映射params参数 if (config.params) { let url = config.url + '?' + tansParams(config.params); url = url.slice(0, -1); config.url = url; } const baseURL = import.meta.env.MODE == 'development' ? config.url : '/prod-api' + config.url; return new Promise((resolve, reject) => { let promise = axios({ method: config.method, url: baseURL, data: config.data, header: config.header || {}, dataType: 'json', timeout: config.timeout || 8000, }); //处理返回 promise .then((res) => { resolve(res.data); }) .catch((err) => { reject(err); }); }); }