Explorar el Código

封装统一网络请求工具类

ChenGanBin hace 2 años
padre
commit
ee633b1c45
Se han modificado 2 ficheros con 94 adiciones y 1 borrados
  1. 78 0
      src/core/http.ts
  2. 16 1
      src/pages/index/index.vue

+ 78 - 0
src/core/http.ts

@@ -0,0 +1,78 @@
+import Taro from "@tarojs/taro";
+
+interface HttpConfig<D = any, R = any> {
+
+  /** 开发者服务器接口地址 */
+  url: string;
+
+  /** 请求的参数 */
+  data: D;
+
+  /**  HTTP 请求方法 */
+  method: "GET" | "POST";
+
+  /** 接口调用成功的回调函数 */
+  success: (result: JsonResponse<R>) => void
+}
+
+interface SuccessCallbackResult<T = any> {
+  /** 开发者服务器返回的数据 */
+  data: JsonResponse<T>
+  /** 开发者服务器返回的 HTTP 状态码 */
+  statusCode: number
+  /** 调用结果 */
+  errMsg: string
+}
+
+const showErrorToast = function (msg: string) {
+  Taro.showToast({
+    title: msg,
+    icon: 'error',
+    duration: 2000
+  });
+}
+
+const handler = function (res: SuccessCallbackResult, fn: Function) {
+  if (res.statusCode == 200) {
+    // TODO 要做业务状态判断
+    if (res.data.success) {
+      fn(res.data.data);
+    } else {
+      showErrorToast(res.data.msg);
+    }
+    return;
+  }
+
+  if (res.statusCode == 400 || res.statusCode == 403) {
+    showErrorToast("请登录");
+    // TODO 跳转登录
+    return;
+  }
+
+  if (res.statusCode == 404) {
+    showErrorToast("请求接口错误");
+  } else if (res.statusCode == 500) {
+    showErrorToast("系统内部发生异常");
+  }
+  console.error("网络调用异常:", res);
+}
+
+const httpClient = function (config: HttpConfig) {
+  Taro.request({
+    url: BASE_URL + config.url,
+    header: {
+      "Authorization": Taro.getStorageSync("token")
+    },
+    method: config.method,
+    data: config.data,
+    success: function (res) {
+      handler(res, config.success);
+    },
+    fail(res) {
+      showErrorToast("服务调用发生异常");
+      console.error("服务调用发生异常", res);
+    },
+  })
+}
+
+export default httpClient;

+ 16 - 1
src/pages/index/index.vue

@@ -10,6 +10,7 @@
       <nut-button type="primary" @click="login()">登录</nut-button>
       <nut-button type="primary" @click="upload()">上传文件</nut-button>
       <nut-button type="primary" @click="download()">下载文件</nut-button>
+      <nut-button type="primary" @click="http()">http封装</nut-button>
     </view>
     <nut-toast :msg="msg2" v-model:visible="show" :type="type" :cover="cover" />
   </view>
@@ -20,6 +21,8 @@
 import Taro from '@tarojs/taro';
 import { reactive, toRefs } from 'vue';
 import { Dongdong } from '@nutui/icons-vue-taro';
+import httpClient from '../../core/http';
+
 export default {
   name: 'Index',
   components: {
@@ -130,8 +133,20 @@ export default {
         }
       })
     };
+
+    const http = () => {
+      httpClient({
+        url: "/oss/test",
+        method: "GET",
+        data: {},
+        success(result: string) {
+          console.log("成功啦", result);
+        }
+      });
+    }
+
     return {
-      ...toRefs(state), handleClick, login, upload, download
+      ...toRefs(state), handleClick, login, upload, download, http
     }
   }
 }