123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- import { host, device_type } from "./constants";
- function showError(error) {
- const errorText = error.statusCode !== 200 ? error.errMsg : error.data.msg;
- uni.showToast({
- title: `发生错误: ${errorText}`,
- duration: 2000,
- icon: "none",
- });
- throw new Error(errorText);
- }
- function getType(data, option) {
- // 获取请求方式
- let token = uni.getStorageSync("token");
- var method = typeof option == "string" ? option : option.method;
- var type = {
- method,
- header: {
- // 'content-type': 'application/x-www-form-urlencoded'
- "Content-Type": "application/json; charset=utf-8",
- "JWT-TOKEN": token,
- "XX-Device-Type": device_type,
- ...option.header,
- },
- };
- // 判断是否为数组
- if (data instanceof Array) {
- // 数组不需要展开
- type.data = data;
- } else if (data instanceof Object) {
- type.data = {
- ...data,
- };
- } else {
- type.data = data;
- }
- return type;
- }
- /**
- * @param {Object} url 接口地址
- * @param {Object/String} option 接口配置
- * option类型为string时等同于{method: xxx}
- * @param {String} option.host 接口域名
- * @param {String} option.method 接口类型
- * @param {Object} data 接口传参
- */
- function request(url, option, data = {}, noLoading) {
- if (!noLoading) {
- uni.showLoading();
- }
- var fullUrl;
- if (typeof option == "object" && option.host) {
- fullUrl = option.host + url;
- } else {
- fullUrl = host + "/api/" + url;
- }
- var option = {
- url: fullUrl,
- ...getType(data, option),
- };
- console.log({
- ...option,
- header: null,
- });
- return uni.request(option).then(
- (res) => {
- if (!noLoading) {
- uni.hideLoading();
- }
- const response = res[1];
- if (!response || !response.data) {
- uni.showToast({
- title: "网络异常,请稍后再试",
- icon: "none",
- });
- }
- const code = response.data.code;
- if (typeof option == "object" && option.host) {
- if (response.statusCode !== 200) {
- showError(response);
- }
- } else {
- if (code == 602 || code == 601 || code == 603) {
- uni.showModal({
- title: "提示",
- content: "登录已过期,请重新登录",
- showCancel: false,
- success: (res) => {
- uni.reLaunch({
- url: "../login/login",
- });
- },
- });
- return;
- }
- // 判断是否是jinke接口返回的内容
- if (response.data.status == 100) return response.data.data;
- if (code !== 200) {
- showError(response);
- // console.error(response)
- // uni.showToast({
- // title: `获取数据失败: ${response.data.msg}`,
- // icon: "none"
- // });
- }
- }
- return response.data;
- },
- (error) => {
- console.log(error);
- }
- );
- }
- export default request;
|