import Taro from "@tarojs/taro"; import {ApiOptions} from "../../types/request"; import {type} from "os"; const requestInterceptor = (chain: Taro.Chain) => { const requestParams = chain.requestParams const token = Taro.getStorageSync('token') if (token) { requestParams.header = { ...requestParams.header, token: token.value } } return chain.proceed(requestParams) } class CustomRequest { BASE_API: string public constructor() { this.BASE_API = process.env.TARO_APP_BASE_API Taro.addInterceptor(requestInterceptor) } 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() const jsonResult = result.data if (jsonResult.code !== 200) { if ([401].includes(jsonResult.code)) { //todo 重新登录 跳转登录页 提示错误 } Taro.showToast({ title: jsonResult.message, icon: 'none', mask: true, duration: 2000 }).then() reject(jsonResult); } resolve(jsonResult); }, fail: (res) => { Taro.hideLoading() Taro.showToast({ title: res.errMsg, icon: 'none', mask: true, duration: 2000 }).then() reject(res.errMsg); console.log(res.errMsg, '000') } }) }) } get(url: string, params?: object, options: ApiOptions = {loading: false}): Promise> { 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> { 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