import store from "../store/index.js"; import { errorCode } from "./commonDicts.js"; export const timeout = 1000 * 60; import { showLoading,hideLoading } from "./loading.js"; // 通用请求头设定 // const ajaxHeader = 'x-ajax'; const sessionIdHeader = 'Authorization'; const install = (Vue, vm) => { uni.$u.http.setConfig((config) => { // const { ip, port, folder } = store.state.user.netConfig; // /* config 为默认全局配置*/ // config.baseURL = ip + ":" + port + folder; config.timeout = timeout; // #ifdef APP-PLUS config.sslVerify = false, // #endif config.custom = { loading : true, loadingText : "正在加载…", } return config }) // 请求拦截 uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作 const { ip, port, folder } = store.state.user.netConfig; const baseURL = ip + (port ? ":" + port : "") + folder; /* 根域名 */ // 处理请求url的逻辑 // 如果是完整的URL(包含http://或https://)或者是本地Mock服务器请求,则不拼接baseURL const isFullUrl = /^https?:\/\//i.test(config.url); const isMockRequest = config.url.includes('localhost:3001') || config.url.includes('192.168.0.243:3001') || config.url.startsWith('/prod-api'); if (!isFullUrl && !isMockRequest) { config.url = baseURL + config.url; } if(config.custom.loading){ const { loadingText } = config.custom; const { timeout } = config; showLoading({loadingText,loadingTime : timeout}); } // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{} config.data = config.data || {} // config.header['Content-Type'] = 'application/json;charset=utf-8' // // 默认指定返回 JSON 数据 // if (!config.header[ajaxHeader]){ // config.header[ajaxHeader] = 'json'; // } // 是否需要设置 token if (!config.header[sessionIdHeader]) { const token = store.state.user.token; const system = store.state.user.belongSystem; if(token){ config.header[sessionIdHeader] = token; if (system) { if (system.id) config.header['belongSystemId'] = system.id if (system.systemName) config.header['belongSystemName'] = encodeURI(system.systemName) } } // else{ // uni.reLaunch({ // url : "/pages/login/index" // }) // } } return config }, config => { // 可使用async await 做异步操作 return Promise.reject(config) }) // 响应拦截 uni.$u.http.interceptors.response.use((res) => { /* 对响应成功做点什么 可使用async await 做异步操作*/ hideLoading(); // 未设置状态码则默认成功状态 const code = res.data.code || 200; // 获取错误信息 const msg = errorCode[code] || res.data.msg || errorCode['default']; // 登录过期 if (code === 401) { uni.$u.toast("登录过期") uni.reLaunch({ url : "/pages/login/index" }); }else if(code === 500){ uni.$u.toast(msg); if(["登录状态已过期","令牌不能为空"].includes(msg)){ uni.reLaunch({ url : "/pages/login/index" }); } return Promise.reject(msg) } return res.data === undefined ? {} : res.data }, (response) => { const { errMsg } = response; if (errMsg.includes("timeout")) { uni.$u.toast("请求超时,请重试") }if(errMsg.includes("fail")){ uni.$u.toast("服务器异常"); } hideLoading(); return Promise.reject(response) }) } export default { install }