ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
``` import Taro from "@tarojs/taro"; import { HOST as baseUrl } from "./data"; // 请求连接前缀 let HOST = 'http://weiqitongapp.zhijikeji.com'; // 线上环境 production if (process.env.NODE_ENV != "development") { HOST = 'https://api.app.usexcx.com'; } export default async ({ url = "", method = 'GET', data = {}, header = {}, loading = "" }) => { try { let token = Taro.getStorageSync('token') loading && Taro.showLoading({ title: loading, mask: true }); if (!token) token = await login(); const res = await Taro.request({ url: `${HOST}${url}`, data: { ...data, }, method: method.toUpperCase(), header: { ...header, "Authorization": token, 'Content-Type': 'application/json' } }); // 登录失效 if (res.data.status == 403) { token = await login(); return request({ url, method, data, header, loading }) } Taro.hideLoading(); return res.data } catch (error) { console.log('错误', error); Taro.hideLoading(); } }; export const login = async () => { try { Taro.showLoading({ title: "登录中..." }); const res = await Taro.login(); const resToken = await Taro.request({ url: `${HOST}/apiNode/member/login`, data: { code: res.code, }, }); Taro.setStorageSync('token', resToken.data.data || ""); Taro.hideLoading(); return resToken.data.data || ""; } catch (error) { console.log(error); Taro.hideLoading(); return "" } } export async function downloadFile({ url, header, isPreview = true, fileType = "xls" }) { try { Taro.showLoading({ title: "文件下载中...", mask: true }) let token = Taro.getStorageSync('token') if (!token) { token = await login(); } const res = await Taro.downloadFile({ url: `${baseUrl}/${url}`, header: { ...header, "Authorization": token, }, }); Taro.hideLoading() if (isPreview) { const _res = Taro.openDocument({ filePath: res.tempFilePath, fileType, }); wx.saveFile({ tempFilePath: res.tempFilePath, }) return _res } return res } catch (error) { console.log('文件下载错误', error); Taro.hideLoading() } } export async function upload(path) { try { const res = await Taro.uploadFile({ url: `${baseUrl}/admin/upload/uploadfile`, //仅为示例,非真实的接口地址 filePath: path, name: 'file', }); const _res = JSON.parse(res.data); _res.data = (_res.data || "").replace('http:', 'https:'); return _res } catch (error) { console.error(error); return {}; } } export const uploadImg = async path => { try { let filePath; if (!path) { const res = await Taro.chooseImage({ count: 1, }); filePath = res.tempFilePaths[0]; } else filePath = path const res2 = await Taro.uploadFile({ url: `${baseUrl}/admin/upload/uploadfile`, //仅为示例,非真实的接口地址 filePath: filePath, name: 'file', }); if (res2 && res2.statusCode == 200 && res2.errMsg && res2.errMsg.includes('ok')) { const _res2 = JSON.parse(res2.data); _res2.data = (_res2.data || "").replace('http:', 'https:') return _res2; } return null; } catch (error) { console.log(error); Taro.showToast({ title: "上传失败,请检查文件名、格式!", icon: "none" }) return null; } } ```