安装依赖
执行以下命令安装Flyio
为什么使用Flyio ? 因为能够跨端使用。
yarn add flyio
添加请求拦截文件,使用请求时引入
import Taro, { showToast, hideLoading } from "@tarojs/taro";import Fly from "flyio/dist/npm/wx"; // 根据环境进行修改不同的包import store from "../store"; // 你可能需要拿到获取公共数据进行判断const request = new Fly();const baseURL = "http://localhost:3000";request.config.timeout = 10000; // 超时时间request.config.baseURL = baseURL;const whiteUrl = ['']; // 不拦截的请求url// 发送请求之前拦截request.interceptors.request.use(async config => {if (!whiteUrl.includes(config.url)) {showToast({title: "加载中...",mask: true,icon: "loading"});}const AccessToken = store.getState().user.token; // 如果已登陆,请带上tokenconfig.headers = {...config.headers,Accept: "application/json","content-type": "application/json; charset=utf-8",Authorization: AccessToken && AccessToken.AccessToken};config.body &&Object.keys(config.body).forEach(val => {if (config.body[val] === "") {delete config.body[val];}});config.body = {...config.body};return config;});request.interceptors.response.use(// 处理请求返回数据,如处理返回结构response => {hideLoading();return response.data;},// 错误时的处理async err => {try {const currentUrl = Taro.getCurrentPages()[ //获取当前页面路径Taro.getCurrentPages().length - 1].route;// 根据业务需求处理err} catch (e) {showToast({ title: '错误信息=>', mask: true, icon: "none" });throw e;} finally {setTimeout(() => {hideLoading();}, 3000);}});export default request;
你可能需要
const newRquest = new Fly();// 锁定请求fly.lock(); // 锁住请求,暂时阻止放下走,不执行其他请求fly.unlock() // 解锁请求,将请求解锁,继续往下走
