uni.request基于Promise封装 |
您所在的位置:网站首页 › k20pro参数配置详情 › 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 => { 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); }, }); }); }; |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |