import Taro from "@tarojs/taro"; import {ApiOptions} from "@/types/request"; import {useUserStore} from "@/store/userStore"; /** * 请求拦截器 * @param chain */ const requestInterceptor = (chain: Taro.Chain) => { const requestParams = chain.requestParams const tokenInfo = useUserStore().getTokenInfo() const {header} = requestParams; const customHeader: Record = {} //添加token tokenInfo && (customHeader[tokenInfo.name] = tokenInfo.value); requestParams.header = { ...header, ...customHeader } return chain.proceed(requestParams) } //所有的拦截器 const interceptors = [requestInterceptor]; //注册拦截器 interceptors.forEach((interceptorItem) => Taro.addInterceptor(interceptorItem)); class CustomRequest { BASE_API: string = process.env.TARO_APP_BASE_API; private request(url: string, method: keyof Taro.request.Method, options: ApiOptions, params?: object,): Promise> { return new Promise>((resolve, reject) => { if (options.loading) { Taro.showLoading({ title: '请求中...', }).then() } Taro.request, object>({ url: this.BASE_API + url, data: params, method, ...options, success: (result) => { Taro.hideLoading() if (result.header['Content-Type'] === 'application/octet-stream') { resolve(result.data) return } const jsonResult = result.data if (jsonResult.code !== 200) { if ([401].includes(jsonResult.code)) { // 重新登录 跳转登录页 提示错误 } Taro.showToast({ title: jsonResult.message, icon: 'none', mask: true, duration: 2000 }).then() reject(jsonResult); } else { resolve(jsonResult); } }, fail: (res) => { Taro.hideLoading() Taro.showToast({ title: res.errMsg, icon: 'none', mask: true, duration: 2000 }).then() reject(res.errMsg); } }) }) } get(url: string, params?: object, options: ApiOptions = {loading: false}): Promise> { options.header = { ...options.header, "content-type": 'application/x-www-form-urlencoded' } return this.request(url, "GET", options, params) } post(url: string, params?: object, options: ApiOptions = {loading: false}): Promise> { return this.request(url, "POST", options, params) } delete(url: string, params?: object, options: ApiOptions = {loading: false}): Promise> { options.header = { ...options.header, "content-type": 'application/x-www-form-urlencoded' } return this.request(url, "DELETE", options, params) } put(url: string, params?: object, options: ApiOptions = {loading: false}): Promise> { return this.request(url, "PUT", options, params) } } const api = new CustomRequest(); export default api