|
|
@@ -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;
|