uni.request基于Promise封装

//设置基地址

const baseURL = "https://meituan.thexxdd.cn/api";

import { Base64 } from "js-base64";

//Base64.encode(要加密的字符串);

//Base64.decode(要解密的字符串);

//定义ts接口

interface httpOptions {

  url: string;

  method: "GET" | "POST" | "PUT" | "DELETE";

  data?: any;

}

//处理token的函数

const getToken = () => {

  //读取token

  const token = uni.getStorageSync("wxuser").user_Token || "";

  //拼接冒号

  const strtoken = token + ":";

  //再加密

  const encodeToke = Base64.encode(strtoken);

  //再通过接拼"Basic "传递给后台

  return "Basic " + encodeToke;

};

//返回类型

//基于Promise封装uni.request

const request = (options: httpOptions): Promise<any> => {

  return new Promise((resolve, reject) => {

    //先加载loading

    uni.showLoading({

      title: "玩命加载中。。",

    });

    uni.request({

      url: `${baseURL}/${options.url}`,

      method: options.method,

      data: options.data,

      //请求头配置,通常是token,自定义头信息

      header: {

        authorization: getToken(),

      },

      success(res) {

        console.log("返回结果:::", res);

        uni.hideLoading();

        if (res.statusCode === 200) {

          resolve(res);

        } else if (res.statusCode === 404) {

          uni.showToast({

            title: "文件未找到",

            icon: "none",

          });

        } else if (res.statusCode === 500) {

          uni.showToast({

            title: "服务器错误",

            icon: "none",

          });

        } else if (res.statusCode === 401) {

          uni.showToast({

            title: "没有访问权限",

            icon: "none",

          });

          //跳转到登录页

          uni.navigateTo({

            url: "/pages/login/login",

          });

          return Promise.reject("未授权登录,报错");

        } else if (res.statusCode === 202) {

          uni.showToast({

            title: res.data.msg,

            icon: "none",

          });

        } else if (res.statusCode === 400) {

          uni.showToast({

            title: "表示参数填写错误,往往是开发者填写参数不对造成的",

            icon: "none",

          });

        }

      },

      fail(error) {

        return Promise.reject(error);

      },

    });

  });

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值