import { CustomRequestOptions } from '@/interceptors/request' import { useUserStore } from '@/store' import { currRoute, currFullPath } from "@/utils" export const http = (options: CustomRequestOptions) => { // 1. 返回 Promise 对象 return new Promise>((resolve, reject) => { let temp = { ...options, dataType: 'json', // #ifndef MP-WEIXIN responseType: 'json', // #endif // 响应成功 success(res) { // console.log("options.url:", options.url); // console.log("currRoute:", currRoute()); // console.log("currFullPath:", currFullPath()); // 状态码 2xx if (res.statusCode >= 200 && res.statusCode < 300) { // 特殊处理(非登录页 && 使用自动登录异常) if (options.url == "/api/wx/mini/login" && currRoute().path != "/pages/login/index" && res.statusCode == 200 && res.data.body.res == '1') { uni.setStorageSync("redirectPath", currFullPath()) reject(res) } // 提取核心数据 res.data resolve(res.data as IResData) } else if (res.statusCode === 401) { useUserStore().setToken("") if (options.url == "/api/wx/mini/login") { // 401错误(登录接口) -> 清理用户信息,跳转到登录页 uni.setStorageSync("redirectPath", currFullPath()) useUserStore().clearUserInfo() uni.reLaunch({ url: '/pages/login/index?isLogout=1' }) reject(res) } else { // 401错误(非登录接口) -> 自动刷新token useUserStore().wxLogin().then((token) => { temp.header['X-ACCESS-TOKEN'] = token uni.request(temp) }).catch(() => { reject(res) }) } } else { // 其他错误 -> 根据后端错误信息轻提示 !options.hideErrorToast && uni.showToast({ icon: 'none', duration: 5000, title: (res.data as IResData).message || '请求错误', }) reject(res) } }, // 响应失败 fail(err) { if (!options.hideErrorToast) { uni.showToast({ icon: 'none', title: '网络错误,换个网络试试', }) } reject(err) }, } uni.request(temp) }) } /** * GET 请求 * @param url 后台地址 * @param query 请求query参数 * @returns */ export const httpGet = (url: string, query?: Record) => { return http({ url, query, method: 'GET', }) } /** * POST 请求 * @param url 后台地址 * @param data 请求body参数 * @param query 请求query参数,post请求也支持query,很多微信接口都需要 * @returns */ export const httpPost = ( url: string, data?: Record, query?: Record, ) => { return http({ url, query, data, method: 'POST', }) } http.get = httpGet http.post = httpPost